@testim/testim-cli 4.142.0 → 4.142.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #! /usr/bin/env node
2
2
  "use strict";var CT=Object.create;var ei=Object.defineProperty;var PT=Object.getOwnPropertyDescriptor;var kT=Object.getOwnPropertyNames;var OT=Object.getPrototypeOf,_T=Object.prototype.hasOwnProperty;var v=(s,e)=>()=>(s&&(e=s(s=0)),e);var H=(s,e)=>{for(var t in e)ei(s,t,{get:e[t],enumerable:!0})},nd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of kT(e))!_T.call(s,n)&&n!==t&&ei(s,n,{get:()=>e[n],enumerable:!(r=PT(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?CT(OT(s)):{},nd(e||!s||!s.__esModule?ei(t,"default",{value:s,enumerable:!0}):t,s)),Fe=s=>nd(ei({},"__esModule",{value:!0}),s);var Be={};H(Be,{log:()=>U,measure:()=>DT});function U(...s){if(!od)return;let e=Date.now();console.log(`${e-LT} ${e-id} `,...s),id=e}function DT(s,e){if(!od)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var od,LT,id,je=v(()=>{"use strict";od=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,LT=Date.now(),id=Date.now()});var Vt,Ur=v(()=>{"use strict";Vt="element-6066-11e4-a52e-4f735466cecf"});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function He(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function Xa(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function ke(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var Qa=v(()=>{"use strict"});var ec,ad,cd,ci=v(()=>{ec={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},ad={"@applitools/eyes-sdk-core":"13.11.34-legacy.1","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"2.1.3","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.3",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",express:"4.21.1",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"1.1.4",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"4.9.18",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.8.0","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"7.0.0","ua-parser-js":"0.7.39","unzip-stream":"0.3.4","validate-npm-package-name":"3.0.0",webdriverio:"8.40.6",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},cd={node:">= 18.0.0"}});var ks,UT,ld,ud,pd,li,Os,dd,fe,md,fd,ui,$e,tc,gd,pi,hd,IR,RR,yd,bd,_s,Td,wd,vd,Sd,rc,sc,nc,ic,Ed,Ls,Id,oc,de=v(()=>{"use strict";ks=process.env.SERVICES_HOST||"https://services.testim.io",UT="https://testimstatic.blob.core.windows.net",ld="https://tstresultfiles.azureedge.net";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:ks,ks=process.env.SERVICES_HOST);ud=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),pd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),li=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Os=process.env.EDITOR_URL,dd=process.env.WEBSOCKET_HOST||`${ks}/ws`,fe=ks,md=parseInt(process.env.LOGGER_CONSOLE||"0",10),fd=parseInt(process.env.LOGGER_DEBUG||"0",10),ui=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),$e=parseInt(process.env.IS_ON_PREM||"0",10),tc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,gd=parseInt(process.env.DEBUG_MODE||"0",10),pi=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,hd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",IR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),RR=process.env.APPIUM_VERSION||"1.10.1",yd=process.env.GATEWAY_URL,bd=process.env.EXTENSION_SERVICES_HOST||ks,_s=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:UT,Td=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:ld,wd=ld,vd=5*60*1e3,Sd=40,rc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",sc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",nc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",ic=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Ed=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Ls=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Id=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,oc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var Rd,di,Ad=v(()=>{"use strict";Rd=I(require("superagent")),di=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=process.env.CORALOGIX_PRIVATE_KEY||"d0eb01da-f966-1663-63c6-8871225d7c39",this.applicationName=e.applicationName,this.subsystemName=e.subsystemName,this.flushIntervalMs=e.flushIntervalMs||2e3,this.maxBufferedLogsCount=e.maxBufferedLogsCount||50,this.interval=setInterval(()=>this.flushLogs(),this.flushIntervalMs)}addLog(e){this.logs.push(e),this.logs.length>=this.maxBufferedLogsCount&&this.flushLogs()}setProxy(e){this.proxy=e}async waitForFlush(){clearInterval(this.interval),await this.flushLogs()}async flushLogs(){try{if(this.logs.length===0)return;let e={applicationName:this.applicationName,subsystemName:this.subsystemName,logEntries:[...this.logs]};this.logs=[];let t=Rd.default.post(this.url).set("Content-Type","application/json; charset=UTF-8").set("Authorization",`Bearer ${this.token}`).send(e);this.proxy&&t.proxy(this.proxy),await t}catch{}}}});var Cd={};H(Cd,{CoralogixTransport:()=>ac});var xd,FT,BT,ac,Pd=v(()=>{"use strict";xd=I(require("winston-transport"));Ad();FT={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},BT=["err","error","reason","e"],ac=class extends xd.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new di({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...l}=t,c={...a,...l},d={severity:FT[i],text:o,category:n||this.category};c.className&&(d.className=c.className),c.methodName&&(d.methodName=c.methodName),c.threadId&&(d.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let m=!1;a instanceof Error&&(m=!0,c.msg=a.message+a.stack,o&&(c.msg=`${o}
3
- ${c.msg}`));for(let u of BT)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(o&&!m&&(c.msg=o),d.text=JSON.stringify(c)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});var fc={};H(fc,{getLogger:()=>C,sessionPlayerLoggerFormatter:()=>uc,setExecutionId:()=>pc,setProjectId:()=>dc,setProxyUri:()=>mc});function WT(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!$e){let{CoralogixTransport:r}=(Pd(),Fe(Cd)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(md){let r={depth:5,colors:!0};s.push(new pt.transports.Console({format:pt.format.combine(pt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),pt.format.timestamp({format:"HH:mm:ss:SSS"}),pt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${fi.inspect(n.meta,r)}`))}))}return[s,e,t]}function pc(s){cc=s}function dc(s){Dd=s}function mc(s){$e||!s||HT(s)}function Od(s){return{projectId:Dd,time:new Date().toISOString(),...cc&&!s&&{executionId:cc}}}function C(s){return new lc(KT.child({category:s}))}var _d,pt,fi,mi,Ld,jT,$T,kd,uc,VT,GT,HT,qT,zT,KT,cc,Dd,lc,W=v(()=>{"use strict";_d=I(require("node:os")),pt=I(require("winston"));de();fi=I(require("node:util")),mi=I(require("chalk")),Ld=I(require("dayjs"));F();jT=_d.hostname(),$T=Ze();kd={depth:5,colors:!0},uc=(s,e,t)=>{let r=`[${(0,Ld.default)().format("HH:mm:ss:SSS")}]`,n=fi.inspect(e,kd),i=fi.inspect(t,kd);return`${mi.default.white(r)} ${mi.default.reset()}SessionPlayer-${mi.default.red(s)} ${n} ${i}`},[VT,GT,HT]=WT(),qT=fd?"debug":"info",zT={release:Boolean(!1),branch:"runner-v4.142.0"},KT=pt.createLogger({levels:pt.config.syslog.levels,level:qT,transports:VT,defaultMeta:{name:"runner",hostname:jT,nodeVersion:process.version,runnerVersion:$T,...zT}}),cc=null,Dd=null;lc=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Od(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Od(n)})}catch{}}}waitForFlush(){return GT()}}});var bi,Fr,x,Gt,lr,St,gi,Br,oe,Ds,et,Ht,Et,hi,jr,yi,Ms,Y=v(()=>{"use strict";bi=require("p-retry"),Fr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},x=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Gt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},lr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},St=class extends bi.AbortError{},gi=class extends bi.AbortError{},Br=class extends bi.AbortError{},oe=class extends Error{},Ds=class extends Error{},et=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Ht=class extends et{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Et=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},hi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},jr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},yi=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Ms=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function gc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ae(s){return(0,Ud.setTimeout)(s)}function hc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function ce(s,e,t="Timeout Error"){li&&!Md&&(Md=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new oe(t);return e=li?Number(li)||6e5:e,Promise.race([s,ae(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Nd||=(await import("p-limit")).default;let r=Nd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function qt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Ud,Md,Nd,yc=v(()=>{"use strict";Ud=require("timers/promises");Y();de();Md=!1});var Us,Fd,JT,Ns,Bd,YT,XT,jd,$d=v(()=>{"use strict";Us=I(require("lodash"));de();Fd=require("dns");W();yc();JT=C("http-request-counters"),Ns=!1,Bd=async()=>{if($e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>Fd.promises.lookup(t)));return e||(Ns=!0),e}catch{return JT.error("network connectivity test failed"),Ns=!0,!1}},YT=Us.throttle(Bd,10*1e3),XT=60*1e3*15,jd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},XT)}function t(n,i=n.name){return async function(...o){e(s.call,i);try{let a=await n.call(null,...o);return e(s.success,i),a}catch(a){throw e(s.fail,i),Ns||YT(),a}}}async function r(){if(Ns||!await Bd())return!1;let n=Us.sum([...s.fail.values()]),i=Us.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Ns,t}});var qe={};H(qe,{deleteReq:()=>Fs,didNetworkConnectivityTestFail:()=>Ic,download:()=>Sc,get:()=>be,getFullRes:()=>rw,getText:()=>js,head:()=>sw,isNetworkHealthy:()=>Ec,post:()=>We,postForm:()=>Bs,postText:()=>wc,put:()=>vc});function ZT(){return global.caFileContent}function ew(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function tw(){return!dt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(dt.default),global.proxyUri}function ur(s,e=!1){let t=ZT();t&&s.ca(t);let r=!e&&tw();r&&s.proxy(r)}async function Wd(s,e,t={},r=$r,n=0){let i=dt.default.post(s).send(e).timeout(r).set(t);ur(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Tc(s,e,t={},r=$r,{isBinary:n=!1,skipProxy:i=!1}={}){let o=dt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),ur(o,i),await o}var dt,bc,tt,$r,QT,Lt,Fs,We,Bs,js,wc,be,rw,sw,vc,Sc,Ec,Ic,Ve=v(()=>{"use strict";dt=I(require("superagent"));W();$d();bc=C("http-request"),tt=jd(),$r=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,QT=6e4;Lt=(s,e,t)=>{let r=e.response;e.response instanceof dt.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw bc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Fs=tt(async(s,e={},t={},r=$r)=>{try{let n=dt.default.delete(s).send(e).timeout(r).set(t);ur(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Lt("failed to delete request",n,{url:s})}}),We=tt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await Wd(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Lt("failed to post request",i,{url:s})}});Bs=tt(async(s,e,t,r={},n=$r)=>{let i=dt.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),ur(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Lt("failed to post request",o,{url:s})}});js=tt(async(s,e,t)=>{try{return(await Tc(s,e,t)).text}catch(r){return Lt("failed to getText request",r,{url:s,query:e})}}),wc=tt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Wd(s,e,t,r,n)).text}catch(i){return Lt("failed to post request",i,{url:s})}}),be=tt(async(s,e,t,r,n)=>{try{return(await Tc(s,e,t,r,n)).body}catch(i){return Lt("failed to get request",i,{url:s,query:e})}}),rw=tt((s,e,t,r)=>Tc(s,e,t,r)),sw=tt(async s=>{let e=dt.default.head(s).timeout($r);ur(e);try{return await e}catch(t){return Lt("failed to head request",t,{url:s})}}),vc=tt(async(s,e,t={},r=$r)=>{let n=dt.default.put(s).send(e).timeout(r).set(t);ur(n);try{return(await n).body}catch(i){return Lt("failed to put request",i,{url:s})}}),Sc=tt(async s=>{bc.info("start to download",{url:s});let e=dt.default.get(s).timeout(QT).buffer(!0).parse(ew);ur(e);try{let t=await e;return bc.info("finished to download",{url:s}),t}catch(t){return Lt("failed to download",t,{url:s})}}),Ec=tt.isNetworkHealthy,Ic=tt.didNetworkConnectivityTestFail});function mt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Dt.resolve(__dirname,"../../"):s=Dt.resolve(__dirname,""),s):process.cwd()}function Ti(s,e){return ke(s)?e||Dt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Dt.basename(s)}function Ze(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function xc(){try{return cd.node}catch{return""}}async function Hd(s,e,t=!0){let r=await rt.promises.readdir(s,{withFileTypes:!0});await rt.promises.mkdir(e,{recursive:t});for(let n of r){let i=Dt.join(s,n.name),o=Dt.join(e,n.name);n.isDirectory()?await Hd(i,o):await rt.promises.copyFile(i,o)}}async function he(s){try{return await rt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Dt,Vd,Gd,rt,nw,Mt,ze,wi,Rc,st,Ac,qd=v(()=>{"use strict";Dt=I(require("path"));Qa();ci();Vd=I(require("unzip-stream")),Gd=I(require("p-retry")),rt=require("fs"),nw=3;Mt=async s=>{let e=await Promise.resolve().then(()=>(Ve(),qe));return(0,Gd.default)(()=>e.download(s),{retries:nw,factor:1})},ze=async(s,e)=>{let t=await Mt(s);return rt.promises.writeFile(e,t.body)};wi=async(s,e)=>{let t=Ti(s,e);return ke(s)?ze(s,t):rt.promises.copyFile(s,t)},Rc=async s=>ke(s)?Mt(s):rt.promises.readFile(s),st=async(s,e)=>await(0,rt.createReadStream)(s).pipe(Vd.Extract({path:e})),Ac=s=>(0,rt.statSync)(s).size/1e6});var Nt={};H(Nt,{APPIUM_SESSION_MESSAGE:()=>_c,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>vi,MOBILE_RUN_SKIP_REASON:()=>Oc,gridMessages:()=>ft,gridTypes:()=>L,mobileWeb:()=>Pc,runnerStatus:()=>Cc,runnerTestStatus:()=>me,socketEventTypes:()=>It,stepResult:()=>Ws,test:()=>kc,testRunStatus:()=>$s,testStatus:()=>Ke,timeoutMessages:()=>Me});var Me,$s,Cc,me,Ke,ft,Pc,kc,It,q,L,Ws,vi,Oc,_c,ie=v(()=>{"use strict";Me={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},$s={COMPLETED:"completed"},Cc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Ke={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ft={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Pc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},kc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},It={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},L={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Ws={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error"},vi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Oc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},_c={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"}});function Vs(s,e){var t,r,n;return(t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(i=>{var o;return(o=i.runConfig)==null?void 0:o.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function iw(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var Gs,zd,Je,ow,aw,cw,lw,uw,Lc,Dc,Kd=v(()=>{"use strict";ie();Gs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},zd=s=>Boolean(s.resultId&&s.source==="remote-run"),Je=(s,e)=>s.testStatus===Ke.QUARANTINE&&!zd(e)&&!e.runQuarantinedTests;ow=s=>Boolean(s.loginMode),aw=s=>Boolean(s.tunnelOnlyMode),cw=s=>Boolean(s.createPrefechedData),lw=s=>Boolean(s.installLazyDepsMode),uw=s=>Boolean(s.agentMode),Lc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Dc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Ei(s=0){return Si.default.duration(s).format("HH:mm:ss.SSS")}function Mc(s=0){return Si.default.duration(s).asSeconds()}var Si,Jd,Yd=v(()=>{"use strict";Si=I(require("dayjs")),Jd=I(require("dayjs/plugin/duration"));Si.default.extend(Jd.default)});var Hs,Wr,zt,Xd,Vr,Qd=v(()=>{"use strict";ie();Hs=s=>!(!s||"fileName"in s),Wr=(s,e)=>{if(e===L.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},zt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Xd=s=>s===L.TESTIM_TVC,Vr=(s,e)=>Xd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Nc(s=4e3){let e=process.memoryUsage(),t=r=>Math.round(r/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>s,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var Zd=v(()=>{"use strict"});var J={};H(J,{OSS:()=>Gr,TESTIM_BROWSER_DIR:()=>Ut,buildBasicHeader:()=>Xa,calcPercentile:()=>Ai,copyDir:()=>Hd,delay:()=>ae,doesPathExist:()=>he,download:()=>Mt,downloadAndSave:()=>ze,extractElementId:()=>Oe,getArgsOnRemoteRunFailure:()=>iw,getBrowserInfo:()=>dw,getCdpAddressForHost:()=>mr,getCliLocation:()=>mt,getDuration:()=>Ei,getDurationSec:()=>Mc,getEnginesVersion:()=>xc,getEnvironmentGitBranch:()=>dr,getLinksFromUnescapeHTML:()=>Ks,getLocalFileSizeInMB:()=>Ac,getMemorySnapshot:()=>Nc,getPlanType:()=>Ri,getRunConfigByBrowserName:()=>qs,getRunnerVersion:()=>Ze,getSource:()=>wi,getSourceAsBuffer:()=>Rc,getSourcePath:()=>Ti,getTestUrl:()=>He,getUniqBrowsers:()=>Vs,groupTestsByRetries:()=>Fc,guid:()=>re,hasTestPlanFlag:()=>Gs,isAgentMode:()=>uw,isAppFromDevice:()=>Hs,isAppFromDeviceDisabled:()=>Vr,isCreatePrefetchedDataMode:()=>cw,isInstallLazyDepsMode:()=>lw,isLoginMode:()=>ow,isMobileProject:()=>zt,isPromise:()=>gc,isQuarantineAndNotRemoteRun:()=>Je,isRemoteRun:()=>zd,isTestimVirtualGrid:()=>Xd,isTunnelOnlyMode:()=>aw,isURL:()=>ke,promiseAbort:()=>hc,promiseFromCallback:()=>qt,promiseMap:()=>se,promiseTimeout:()=>ce,removePropertyFromObject:()=>Ii,replaceArgsWithNoDashes:()=>Lc,sanitizeNumberValue:()=>pr,shouldBlockVirtualIosBuild:()=>Wr,spreadObjectToArgs:()=>Dc,unescapeHTML:()=>zs,unzipFile:()=>st});function pr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function dw(s){return s=s.toLowerCase(),Uc.find(e=>e.browserValue===s)}function qs(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Uc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Uc[0],n=Gr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=Gr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=Gr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=Gr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=Gr.find(i=>i.bs.platform===t.platform))),Hr.merge(r,n)}function dr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Ii(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Ii(s[r],e,t))}function Oe(s){return s.ELEMENT||s[Vt]}function Ri(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Fc(s=[]){return Hr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=Hr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function zs(s){return sm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Ks(s){return[...sm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function mr(s,e){let t=await Promise.resolve().then(()=>(Ve(),qe));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var em,Hr,tm,rm,pw,Ut,Gr,Uc,Ai,sm,F=v(()=>{"use strict";em=I(require("os")),Hr=I(require("lodash")),tm=I(require("path")),rm=require("linkedom");Ur();qd();Kd();Yd();Qa();yc();Qd();Zd();pw=em.homedir(),Ut=tm.join(pw,".testim-browser-profile"),Gr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Uc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Ai=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};sm=new rm.DOMParser});var Bc={};H(Bc,{$schema:()=>mw,default:()=>bw,definitions:()=>fw,properties:()=>yw,required:()=>hw,type:()=>gw});var mw,fw,gw,hw,yw,bw,nm=v(()=>{mw="http://json-schema.org/draft-07/schema#",fw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},gw="object",hw=["entries"],yw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},bw={$schema:mw,definitions:fw,type:gw,required:hw,properties:yw}});async function pm(){try{return await ce(xi.promises.readFile(Oi()).then(async s=>{let e=await um;return vw(e,s)}),3e4)}catch{return{}}}function vw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=zr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Ft(s,e,t=Tw,r=void 0){return async()=>{if(!am)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Sw(e);if(i)return Js.debug("cache hit:",{fnName:e}),i;if(Js.debug("cache miss:",{fnName:e}),!cm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Ew(e,o,t),o}}async function Sw(s){let t=(await _i)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Ew(s,e,t){if(jc)throw Js.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await _i;r[s]={value:e,expiry:Date.now()+t},lm=new Promise(n=>{ki=n}),ww(r)}catch{Js.error("failed updating cache")}}async function Kr(){let s=await _i;Object.keys(s).forEach(e=>{delete s[e]})}function dm(s){am=s}function Iw(s=!0){cm=s}async function mm(){try{return jc=!0,await lm}finally{jc=!1}}function fm(s){Pi=s,_i=pm()}var xi,Ci,zr,im,Js,Pi,om,ki,am,cm,jc,lm,um,Tw,Oi,_i,ww,gm,hm,tA,ym,Kt=v(()=>{"use strict";xi=I(require("fs")),Ci=I(require("path")),zr=I(require("crypto"));F();im=require("lodash");W();Js=C("local cache"),Pi=Ci.resolve(mt(),"testim-cache"),am=!0,cm=!0,jc=!1,lm=new Promise(s=>{ki=s}),um=new Promise(s=>{om=s}),Tw=1e3*60*60*3,Oi=()=>Ci.resolve(Ci.resolve(Pi,"testim.cache"));_i=pm(),ww=(0,im.debounce)(async s=>{let e;try{let t=await um,r=zr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=zr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await he(Pi)||await xi.promises.mkdir(Pi,{recursive:!0}),await xi.promises.writeFile(Oi(),a)}catch(t){Js.error("failed saving cache",{err:t}),e=t}ki(e?{success:!1,error:e}:{success:!0})},200);gm=om,hm=dm.bind(void 0,!1),tA=dm.bind(void 0,!0),ym=()=>Iw(!1)});function Li(){return{cliLocation:mt(),userInfo:Jr.userInfo(),platform:Jr.platform(),release:Jr.release()}}var Jr,$c=v(()=>{"use strict";Jr=I(require("os"));F()});function Rw(s){try{return Di.resolve(Di.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function Jt(s){let e=Rw(s);return require(e)}var Di,Ys=v(()=>{"use strict";Di=I(require("path"))});function Aw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function xw(s){return/The "to" argument must be of type string./.exec(s)}function vm(s,e,t){let r=Aw(s),n=xw(s);return r||n?(wm.info("Failed to install package due to insufficient write access",{...Li(),package:t,path:r}),console.error(`
3
+ ${c.msg}`));for(let u of BT)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(o&&!m&&(c.msg=o),d.text=JSON.stringify(c)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});var fc={};H(fc,{getLogger:()=>C,sessionPlayerLoggerFormatter:()=>uc,setExecutionId:()=>pc,setProjectId:()=>dc,setProxyUri:()=>mc});function WT(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!$e){let{CoralogixTransport:r}=(Pd(),Fe(Cd)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(md){let r={depth:5,colors:!0};s.push(new pt.transports.Console({format:pt.format.combine(pt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),pt.format.timestamp({format:"HH:mm:ss:SSS"}),pt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${fi.inspect(n.meta,r)}`))}))}return[s,e,t]}function pc(s){cc=s}function dc(s){Dd=s}function mc(s){$e||!s||HT(s)}function Od(s){return{projectId:Dd,time:new Date().toISOString(),...cc&&!s&&{executionId:cc}}}function C(s){return new lc(KT.child({category:s}))}var _d,pt,fi,mi,Ld,jT,$T,kd,uc,VT,GT,HT,qT,zT,KT,cc,Dd,lc,W=v(()=>{"use strict";_d=I(require("node:os")),pt=I(require("winston"));de();fi=I(require("node:util")),mi=I(require("chalk")),Ld=I(require("dayjs"));F();jT=_d.hostname(),$T=Ze();kd={depth:5,colors:!0},uc=(s,e,t)=>{let r=`[${(0,Ld.default)().format("HH:mm:ss:SSS")}]`,n=fi.inspect(e,kd),i=fi.inspect(t,kd);return`${mi.default.white(r)} ${mi.default.reset()}SessionPlayer-${mi.default.red(s)} ${n} ${i}`},[VT,GT,HT]=WT(),qT=fd?"debug":"info",zT={release:Boolean(!1),branch:"runner-v4.142.2"},KT=pt.createLogger({levels:pt.config.syslog.levels,level:qT,transports:VT,defaultMeta:{name:"runner",hostname:jT,nodeVersion:process.version,runnerVersion:$T,...zT}}),cc=null,Dd=null;lc=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Od(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Od(n)})}catch{}}}waitForFlush(){return GT()}}});var bi,Fr,x,Gt,lr,St,gi,Br,oe,Ds,et,Ht,Et,hi,jr,yi,Ms,Y=v(()=>{"use strict";bi=require("p-retry"),Fr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},x=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Gt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},lr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},St=class extends bi.AbortError{},gi=class extends bi.AbortError{},Br=class extends bi.AbortError{},oe=class extends Error{},Ds=class extends Error{},et=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Ht=class extends et{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Et=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},hi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},jr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},yi=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Ms=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function gc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ae(s){return(0,Ud.setTimeout)(s)}function hc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function ce(s,e,t="Timeout Error"){li&&!Md&&(Md=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new oe(t);return e=li?Number(li)||6e5:e,Promise.race([s,ae(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Nd||=(await import("p-limit")).default;let r=Nd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function qt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Ud,Md,Nd,yc=v(()=>{"use strict";Ud=require("timers/promises");Y();de();Md=!1});var Us,Fd,JT,Ns,Bd,YT,XT,jd,$d=v(()=>{"use strict";Us=I(require("lodash"));de();Fd=require("dns");W();yc();JT=C("http-request-counters"),Ns=!1,Bd=async()=>{if($e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>Fd.promises.lookup(t)));return e||(Ns=!0),e}catch{return JT.error("network connectivity test failed"),Ns=!0,!1}},YT=Us.throttle(Bd,10*1e3),XT=60*1e3*15,jd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},XT)}function t(n,i=n.name){return async function(...o){e(s.call,i);try{let a=await n.call(null,...o);return e(s.success,i),a}catch(a){throw e(s.fail,i),Ns||YT(),a}}}async function r(){if(Ns||!await Bd())return!1;let n=Us.sum([...s.fail.values()]),i=Us.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Ns,t}});var qe={};H(qe,{deleteReq:()=>Fs,didNetworkConnectivityTestFail:()=>Ic,download:()=>Sc,get:()=>be,getFullRes:()=>rw,getText:()=>js,head:()=>sw,isNetworkHealthy:()=>Ec,post:()=>We,postForm:()=>Bs,postText:()=>wc,put:()=>vc});function ZT(){return global.caFileContent}function ew(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function tw(){return!dt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(dt.default),global.proxyUri}function ur(s,e=!1){let t=ZT();t&&s.ca(t);let r=!e&&tw();r&&s.proxy(r)}async function Wd(s,e,t={},r=$r,n=0){let i=dt.default.post(s).send(e).timeout(r).set(t);ur(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Tc(s,e,t={},r=$r,{isBinary:n=!1,skipProxy:i=!1}={}){let o=dt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),ur(o,i),await o}var dt,bc,tt,$r,QT,Lt,Fs,We,Bs,js,wc,be,rw,sw,vc,Sc,Ec,Ic,Ve=v(()=>{"use strict";dt=I(require("superagent"));W();$d();bc=C("http-request"),tt=jd(),$r=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,QT=6e4;Lt=(s,e,t)=>{let r=e.response;e.response instanceof dt.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw bc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Fs=tt(async(s,e={},t={},r=$r)=>{try{let n=dt.default.delete(s).send(e).timeout(r).set(t);ur(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Lt("failed to delete request",n,{url:s})}}),We=tt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await Wd(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Lt("failed to post request",i,{url:s})}});Bs=tt(async(s,e,t,r={},n=$r)=>{let i=dt.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),ur(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Lt("failed to post request",o,{url:s})}});js=tt(async(s,e,t)=>{try{return(await Tc(s,e,t)).text}catch(r){return Lt("failed to getText request",r,{url:s,query:e})}}),wc=tt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Wd(s,e,t,r,n)).text}catch(i){return Lt("failed to post request",i,{url:s})}}),be=tt(async(s,e,t,r,n)=>{try{return(await Tc(s,e,t,r,n)).body}catch(i){return Lt("failed to get request",i,{url:s,query:e})}}),rw=tt((s,e,t,r)=>Tc(s,e,t,r)),sw=tt(async s=>{let e=dt.default.head(s).timeout($r);ur(e);try{return await e}catch(t){return Lt("failed to head request",t,{url:s})}}),vc=tt(async(s,e,t={},r=$r)=>{let n=dt.default.put(s).send(e).timeout(r).set(t);ur(n);try{return(await n).body}catch(i){return Lt("failed to put request",i,{url:s})}}),Sc=tt(async s=>{bc.info("start to download",{url:s});let e=dt.default.get(s).timeout(QT).buffer(!0).parse(ew);ur(e);try{let t=await e;return bc.info("finished to download",{url:s}),t}catch(t){return Lt("failed to download",t,{url:s})}}),Ec=tt.isNetworkHealthy,Ic=tt.didNetworkConnectivityTestFail});function mt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Dt.resolve(__dirname,"../../"):s=Dt.resolve(__dirname,""),s):process.cwd()}function Ti(s,e){return ke(s)?e||Dt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Dt.basename(s)}function Ze(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function xc(){try{return cd.node}catch{return""}}async function Hd(s,e,t=!0){let r=await rt.promises.readdir(s,{withFileTypes:!0});await rt.promises.mkdir(e,{recursive:t});for(let n of r){let i=Dt.join(s,n.name),o=Dt.join(e,n.name);n.isDirectory()?await Hd(i,o):await rt.promises.copyFile(i,o)}}async function he(s){try{return await rt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Dt,Vd,Gd,rt,nw,Mt,ze,wi,Rc,st,Ac,qd=v(()=>{"use strict";Dt=I(require("path"));Qa();ci();Vd=I(require("unzip-stream")),Gd=I(require("p-retry")),rt=require("fs"),nw=3;Mt=async s=>{let e=await Promise.resolve().then(()=>(Ve(),qe));return(0,Gd.default)(()=>e.download(s),{retries:nw,factor:1})},ze=async(s,e)=>{let t=await Mt(s);return rt.promises.writeFile(e,t.body)};wi=async(s,e)=>{let t=Ti(s,e);return ke(s)?ze(s,t):rt.promises.copyFile(s,t)},Rc=async s=>ke(s)?Mt(s):rt.promises.readFile(s),st=async(s,e)=>await(0,rt.createReadStream)(s).pipe(Vd.Extract({path:e})),Ac=s=>(0,rt.statSync)(s).size/1e6});var Nt={};H(Nt,{APPIUM_SESSION_MESSAGE:()=>_c,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>vi,MOBILE_RUN_SKIP_REASON:()=>Oc,gridMessages:()=>ft,gridTypes:()=>L,mobileWeb:()=>Pc,runnerStatus:()=>Cc,runnerTestStatus:()=>me,socketEventTypes:()=>It,stepResult:()=>Ws,test:()=>kc,testRunStatus:()=>$s,testStatus:()=>Ke,timeoutMessages:()=>Me});var Me,$s,Cc,me,Ke,ft,Pc,kc,It,q,L,Ws,vi,Oc,_c,ie=v(()=>{"use strict";Me={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},$s={COMPLETED:"completed"},Cc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Ke={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ft={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Pc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},kc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},It={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},L={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Ws={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error"},vi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Oc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},_c={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"}});function Vs(s,e){var t,r,n;return(t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(i=>{var o;return(o=i.runConfig)==null?void 0:o.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function iw(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var Gs,zd,Je,ow,aw,cw,lw,uw,Lc,Dc,Kd=v(()=>{"use strict";ie();Gs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},zd=s=>Boolean(s.resultId&&s.source==="remote-run"),Je=(s,e)=>s.testStatus===Ke.QUARANTINE&&!zd(e)&&!e.runQuarantinedTests;ow=s=>Boolean(s.loginMode),aw=s=>Boolean(s.tunnelOnlyMode),cw=s=>Boolean(s.createPrefechedData),lw=s=>Boolean(s.installLazyDepsMode),uw=s=>Boolean(s.agentMode),Lc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Dc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Ei(s=0){return Si.default.duration(s).format("HH:mm:ss.SSS")}function Mc(s=0){return Si.default.duration(s).asSeconds()}var Si,Jd,Yd=v(()=>{"use strict";Si=I(require("dayjs")),Jd=I(require("dayjs/plugin/duration"));Si.default.extend(Jd.default)});var Hs,Wr,zt,Xd,Vr,Qd=v(()=>{"use strict";ie();Hs=s=>!(!s||"fileName"in s),Wr=(s,e)=>{if(e===L.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},zt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Xd=s=>s===L.TESTIM_TVC,Vr=(s,e)=>Xd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Nc(s=4e3){let e=process.memoryUsage(),t=r=>Math.round(r/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>s,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var Zd=v(()=>{"use strict"});var J={};H(J,{OSS:()=>Gr,TESTIM_BROWSER_DIR:()=>Ut,buildBasicHeader:()=>Xa,calcPercentile:()=>Ai,copyDir:()=>Hd,delay:()=>ae,doesPathExist:()=>he,download:()=>Mt,downloadAndSave:()=>ze,extractElementId:()=>Oe,getArgsOnRemoteRunFailure:()=>iw,getBrowserInfo:()=>dw,getCdpAddressForHost:()=>mr,getCliLocation:()=>mt,getDuration:()=>Ei,getDurationSec:()=>Mc,getEnginesVersion:()=>xc,getEnvironmentGitBranch:()=>dr,getLinksFromUnescapeHTML:()=>Ks,getLocalFileSizeInMB:()=>Ac,getMemorySnapshot:()=>Nc,getPlanType:()=>Ri,getRunConfigByBrowserName:()=>qs,getRunnerVersion:()=>Ze,getSource:()=>wi,getSourceAsBuffer:()=>Rc,getSourcePath:()=>Ti,getTestUrl:()=>He,getUniqBrowsers:()=>Vs,groupTestsByRetries:()=>Fc,guid:()=>re,hasTestPlanFlag:()=>Gs,isAgentMode:()=>uw,isAppFromDevice:()=>Hs,isAppFromDeviceDisabled:()=>Vr,isCreatePrefetchedDataMode:()=>cw,isInstallLazyDepsMode:()=>lw,isLoginMode:()=>ow,isMobileProject:()=>zt,isPromise:()=>gc,isQuarantineAndNotRemoteRun:()=>Je,isRemoteRun:()=>zd,isTestimVirtualGrid:()=>Xd,isTunnelOnlyMode:()=>aw,isURL:()=>ke,promiseAbort:()=>hc,promiseFromCallback:()=>qt,promiseMap:()=>se,promiseTimeout:()=>ce,removePropertyFromObject:()=>Ii,replaceArgsWithNoDashes:()=>Lc,sanitizeNumberValue:()=>pr,shouldBlockVirtualIosBuild:()=>Wr,spreadObjectToArgs:()=>Dc,unescapeHTML:()=>zs,unzipFile:()=>st});function pr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function dw(s){return s=s.toLowerCase(),Uc.find(e=>e.browserValue===s)}function qs(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Uc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Uc[0],n=Gr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=Gr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=Gr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=Gr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=Gr.find(i=>i.bs.platform===t.platform))),Hr.merge(r,n)}function dr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Ii(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Ii(s[r],e,t))}function Oe(s){return s.ELEMENT||s[Vt]}function Ri(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Fc(s=[]){return Hr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=Hr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function zs(s){return sm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Ks(s){return[...sm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function mr(s,e){let t=await Promise.resolve().then(()=>(Ve(),qe));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var em,Hr,tm,rm,pw,Ut,Gr,Uc,Ai,sm,F=v(()=>{"use strict";em=I(require("os")),Hr=I(require("lodash")),tm=I(require("path")),rm=require("linkedom");Ur();qd();Kd();Yd();Qa();yc();Qd();Zd();pw=em.homedir(),Ut=tm.join(pw,".testim-browser-profile"),Gr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Uc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Ai=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};sm=new rm.DOMParser});var Bc={};H(Bc,{$schema:()=>mw,default:()=>bw,definitions:()=>fw,properties:()=>yw,required:()=>hw,type:()=>gw});var mw,fw,gw,hw,yw,bw,nm=v(()=>{mw="http://json-schema.org/draft-07/schema#",fw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},gw="object",hw=["entries"],yw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},bw={$schema:mw,definitions:fw,type:gw,required:hw,properties:yw}});async function pm(){try{return await ce(xi.promises.readFile(Oi()).then(async s=>{let e=await um;return vw(e,s)}),3e4)}catch{return{}}}function vw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=zr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Ft(s,e,t=Tw,r=void 0){return async()=>{if(!am)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Sw(e);if(i)return Js.debug("cache hit:",{fnName:e}),i;if(Js.debug("cache miss:",{fnName:e}),!cm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Ew(e,o,t),o}}async function Sw(s){let t=(await _i)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Ew(s,e,t){if(jc)throw Js.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await _i;r[s]={value:e,expiry:Date.now()+t},lm=new Promise(n=>{ki=n}),ww(r)}catch{Js.error("failed updating cache")}}async function Kr(){let s=await _i;Object.keys(s).forEach(e=>{delete s[e]})}function dm(s){am=s}function Iw(s=!0){cm=s}async function mm(){try{return jc=!0,await lm}finally{jc=!1}}function fm(s){Pi=s,_i=pm()}var xi,Ci,zr,im,Js,Pi,om,ki,am,cm,jc,lm,um,Tw,Oi,_i,ww,gm,hm,tA,ym,Kt=v(()=>{"use strict";xi=I(require("fs")),Ci=I(require("path")),zr=I(require("crypto"));F();im=require("lodash");W();Js=C("local cache"),Pi=Ci.resolve(mt(),"testim-cache"),am=!0,cm=!0,jc=!1,lm=new Promise(s=>{ki=s}),um=new Promise(s=>{om=s}),Tw=1e3*60*60*3,Oi=()=>Ci.resolve(Ci.resolve(Pi,"testim.cache"));_i=pm(),ww=(0,im.debounce)(async s=>{let e;try{let t=await um,r=zr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=zr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await he(Pi)||await xi.promises.mkdir(Pi,{recursive:!0}),await xi.promises.writeFile(Oi(),a)}catch(t){Js.error("failed saving cache",{err:t}),e=t}ki(e?{success:!1,error:e}:{success:!0})},200);gm=om,hm=dm.bind(void 0,!1),tA=dm.bind(void 0,!0),ym=()=>Iw(!1)});function Li(){return{cliLocation:mt(),userInfo:Jr.userInfo(),platform:Jr.platform(),release:Jr.release()}}var Jr,$c=v(()=>{"use strict";Jr=I(require("os"));F()});function Rw(s){try{return Di.resolve(Di.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function Jt(s){let e=Rw(s);return require(e)}var Di,Ys=v(()=>{"use strict";Di=I(require("path"))});function Aw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function xw(s){return/The "to" argument must be of type string./.exec(s)}function vm(s,e,t){let r=Aw(s),n=xw(s);return r||n?(wm.info("Failed to install package due to insufficient write access",{...Li(),package:t,path:r}),console.error(`
4
4
 
5
5
  Testim failed installing the package ${t||""} due to insufficient permissions.
6
6
  This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
@@ -406,7 +406,7 @@ Please make sure the CLI has stable access to the internet. ${Ic()?"(Internal: n
406
406
  `;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 ha.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 i="The element is not editable",o="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(i)||f.startsWith(o)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ha.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Oe(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=k.flags.overrideAzureStorageUrl.isEnabled(),n=k.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:l,driver:c}=this,d=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,l.testimServicesApi,r,ha);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 Mt(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(`
407
407
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
408
408
  const downloadAndUploadFile = ${iI()};
409
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Qy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ba,Ta,tb=v(()=>{"use strict";ba=require("url");ue();Ta=class extends G{async updateBaseUrl(e){let t=new ba.URL(e),r=new ba.URL(this.context.recordedBaseUrl),n=new ba.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 wa,rb=v(()=>{"use strict";ue();F();wa=class extends G{async performAction(){await ae(this.step.durationMS||0)}}});var va,sb=v(()=>{"use strict";ue();va=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Kn,nb=v(()=>{"use strict";ue();Kn=class extends G{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.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.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}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},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Sa,ib=v(()=>{"use strict";ue();Sa=class extends G{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 ob,Ep,Ip,ab=v(()=>{"use strict";ob=I(require("@applitools/spec-driver-webdriverio"));ci();Te();Ep=class{constructor(){let{EyeSdkBuilder:e}=X(),t=ad["@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:ob.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=X(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Ip=new Ep});var lb,cb,Jn,ub=v(()=>{"use strict";lb=I(require("lodash"));ue();W();ab();cb=C("pixel-validation-step-action"),Jn=class extends G{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Ip.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"};lb.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),cb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){cb.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Ip.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,Rp=v(()=>{"use strict";gs();Y();ca();vs=class extends ir{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:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await fs(i,o,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 oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var or,pb=v(()=>{"use strict";Rp();or=class extends vs{isFailedResult(e){return e===!1}}});var Ea,db=v(()=>{"use strict";Rp();Ea=class extends vs{isFailedResult(e){return!e}}});var Ia,mb=v(()=>{"use strict";gs();ue();Y();Ia=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await ms(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Et?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Or,fb=v(()=>{"use strict";ue();Or=class extends G{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,gb=v(()=>{"use strict";ue();ye=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ra,hb=v(()=>{"use strict";ue();Ra=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));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(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Aa,yb=v(()=>{"use strict";ue();Aa=class extends G{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 oI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function xa(s,e){oI(aI,e),e.registerLocateStepActionUtils(Gn.getUtils(s))}var aI,Ap=v(()=>{"use strict";my();hy();Ry();Ay();Cy();Oy();Dy();My();Ny();Uy();jy();$y();Wy();Hy();Ky();eb();tb();rb();sb();nb();ib();ub();pb();db();mb();fb();gb();hb();yb();aI={locate:Gn,scroll:sa,mouse:na,submit:da,text:oa,"special-key":la,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":ia,"text-validation":qn,"wait-for-text-validation":qn,"select-option":pa,"drop-file":ga,"input-file":ya,hover:ma,navigation:Ta,wheel:fa,sleep:wa,refresh:va,"keyboard-shortcut-step":ua,"api-validation":Kn,"api-action":Kn,"api-code-step":Wt,"extract-text":Sa,"simple-ui-verification":Jn,"wait-for-simple-ui-verification":Jn,"cli-validation-download-file":Or,"cli-wait-for-download-file":Or,"network-validation-step":Or,"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":Ea,"node-package":Ia,"email-code-step":Wt,"cli-email-code-step":or,"sfdc-internal-test-step":Aa,"sfdc-recorded-step":Ra,"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":Or,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var bb,cI,Ss,xp=v(()=>{"use strict";bb=["simple-ui-verification","wait-for-simple-ui-verification"],cI=[...bb,"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=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=cI.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 bb.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 wb={};H(wb,{SeleniumTestPlayer:()=>Yn});var Tb,lI,Yn,Cp=v(()=>{"use strict";F();Tb=require("@applitools/eyes-sdk-core");Nn();Y();W();yp();cy();vp();ta();py();Sp();Te();Ap();xp();lI=C("SeleniumTestPlayer"),Yn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Ss(ra());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=X();this.driver=n??new xr;let d=new ea(this.driver);this.stepActionFactory=new c(d),xa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Qo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=uy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ts(this.driver),FrameLocator:m,portSelector:Zo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Tb.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=i,this.sessionPlayer.playbackManager.previousTestResultId=o,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}=X(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){lI.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(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var kp={};H(kp,{WorkerSelenium:()=>Pp});function pI(s){let{playback:e}=X().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>U(`Got event ${t}`))}var Ca,uI,Pp,Op=v(()=>{"use strict";F();je();Wn();W();Pt();oo();ie();gp();Y();Cp();Te();it();Ca=C("worker-selenium"),uI=1e9,Pp=class extends Ot{initPlayer(t){return new Yn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){U("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new bs(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),U("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),U("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,uI),await this.windowUtils.validatePageIsAvailable(),U("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 St||d||m?new St(`Page '${l}' is not available`):(Ca.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Vi(),initializedFromCache:Gi()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=X(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),pI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await wn(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,Me.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof oe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Ca.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=o.maxKeepAliveGap();f>=3e4&&(Ca.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 o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),U("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),U("right after super.runTestOnce in workerSelenium");let u=await d();return U("right after runSeleniumTest"),u}catch(u){throw Ca.error("failed to run test once",{err:u}),u}}}});var vb,Sb,Ge,dI,mI,_p,Tt,Pa=v(()=>{"use strict";vb=I(require("ora")),Sb=require("jimp");de();Ve();ge();W();ie();Te();le();Ge=C("mobile-grid-service"),dI="https://tdc.tricentis-cloud.com",mI="https://ui.headspin.io",_p=class{constructor(){this.gridsAppIdGetter={[L.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[L.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[L.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[L.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[L.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[L.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===L.TESTIM_TDC||e===L.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===L.TESTIM_HEADSPIN?`${r||rc}/${nc}/devices`:t===L.TESTIM_TDC?`${r||sc}/${nc}/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),i=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:i})}catch(o){throw Ge.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw Ge.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await js(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.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===L.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===L.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([L.BROWSERSTACK,L.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:i,gridId:o}){var a,l,c;if(t===L.TESTIM_HEADSPIN||t===L.TESTIM_TDC){let d=await Ul({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.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,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=X();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Tr(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),Ge.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=X(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await Sb.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/c.width,width:u,height:f}}catch(o){return Ge.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,i,o,a,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ls}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?mI:dI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await be(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:l}=t,c=await this.getTmaDeviceDetails(l,e);return await Tr(a,n,i,o,"RUNNING",{device:c}),Ge.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:c}),c}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(k.flags.allowFixingAppIdStructure.isEnabled()&&(Ge.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Bl({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await pn({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/(Sd*60))+1)*60*1e3,Math.max(vd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[L.BROWSERSTACK]:{name:"Browserstack"},[L.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[L.P_CLOUDY]:{name:"pCloudy"}}[i].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,vb.default)(`uploading app to ${a} please wait..`).start();try{Ge.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Fl({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}`),Ge.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:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,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){Ge.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else Ge.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===L.BROWSERSTACK||f===L.TESTIM_TVC||f===L.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(Ge.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&Ge.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}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:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Ls}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${ic}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?rc:sc}/${ic}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Ed}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&Ge.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===L.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await wc({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 be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await be(e,void 0,i)}},Tt=new _p});function Eb({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"&&!fI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function gI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==L.TESTIM_TDC&&e.type!==L.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 hI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function yI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&k.flags.enableBatchHeadSpin.isEnabled(),d=o&&(k.flags.enableBatchTDC.isEnabled()||k.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=k.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,...k.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:hI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function ka(s){return"id"in s?s.id:s.packageName}function bI(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function TI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=bI(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":ka(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":ka(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:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:ka(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:ka(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Ib({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let l=yI(o.type,i,n);return TI({projectType:s,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function _a({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 La({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===L.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?oc:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":oc:".*")}function wI(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 vI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Oa(s,Es)}}function Rb(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function SI(s){return Rb(s,e=>e.startsWith("browserstack."),"browserstack.")}function EI(s){return Rb(s,e=>!e.startsWith("browserstack."))}function Ab(s){return!s||!xb(s)?"2.0.0":s}function xb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Cb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=xb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Oa(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}function II({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:l}){let{osVersion:c,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=wI(i,s),h=_a({osVersion:c,mobileConfig:m}),g=La({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),y=He(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),T={device:g,os_version:h,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":y,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Lr({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:l})}function RI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=k.flags.enableAppium2pCloudy.isEnabled(),g=_a({osVersion:l,mobileConfig:d}),y=La({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),w={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...w,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Id),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=vI(b)),t="",Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Es}})}function AI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=_a({osVersion:l,mobileConfig:d}),f=La({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,_r.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Cb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},w={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:Ab(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...Oa(h,Es),"sauce:options":{...T,...w,...(0,_r.omit)(g,"appiumVersion")}};return Lr({projectType:s,sessionCaps:b,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=_a({osVersion:l,mobileConfig:d}),f=La({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=SI(n.browserstack),g=(0,_r.omit)(EI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:w}=n.browserstack||{},b=k.flags.enableAppium2BrowserStack.isEnabled();if(b||Cb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":Ab(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},A={"appium:platformVersion":u,"appium:deviceName":f,...Oa(g,Es),"bstack:options":{...E,...(0,_r.omit)(h,"appiumVersion")}};return Lr({projectType:s,sessionCaps:A,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let S={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:w||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Oa(h,"browserstack.")};return Lr({projectType:s,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Ib(s);if(L.TESTIM_TVC===s.gridInfo.type)return II(s);if(L.P_CLOUDY===s.gridInfo.type)return RI(s);if(L.SAUCELABS===s.gridInfo.type)return AI(s);if(L.BROWSERSTACK===s.gridInfo.type)return xI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function PI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((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),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Pb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);Eb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=Tt.getGridConnection(e),l=CI(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=PI(r,i==null?void 0:i.mobile);if(!(0,_r.isEmpty)(T)){let w=Object.entries(T).map(([b,S])=>S.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=w}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=k.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Lp.default)("2m"),f=(0,Lp.default)("12m"),h=pr(k.flags.appiumConnectionRetryCount.getValue(),m),g=pr(k.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function kb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Eb({nativeAppMetadata:r,appPath:i,gridInfo:t}),gI({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 Tt.getGridDirectConnection(t,d),f=Ib({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,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 Ob(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Lr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function _b(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 Lp,_r,Es,fI,Dp=v(()=>{"use strict";Lp=I(require("ms"));le();ie();Pa();_r=require("lodash");F();de();Es="appium:",fI=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var Da,Db=v(()=>{"use strict";Da=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 Ma,Mb=v(()=>{"use strict";F();Ma=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 Mp,Na,Nb=v(()=>{"use strict";W();Mp=C("mobile-frame-locator-mock"),Na=class{foundFrameCallback(){return Mp.info("foundFrameCallback-mock invoked"),{}}locate(){return Mp.info("locate-mock invoked"),{}}async findFrame(){return Mp.info("findFrame-mock invoked"),{}}}});var kI,Fb,Ub,Is,Np=v(()=>{"use strict";kI=I(require("webdriverio")),Fb=require("@applitools/eyes-sdk-core");Db();vp();W();Mb();Sp();Te();Ap();Nb();xp();Ub=C("appium-test-player"),Is=class{constructor(e,t,r,n=kI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=X(),m=new Ma(this.driver);this.stepActionFactory=new c(m),xa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ss(ra()),this.sessionPlayer=new a(e,{tabService:new Da,cookieUtils:void 0,FrameLocator:Na,portSelector:Zo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Fb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,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,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Ub.info("appium session deleted",{...i}))}catch(o){Ub.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=X();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function OI(s){return await be(`${s}/api/status`)}async function Bb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function jb(s){if((await OI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var $b=v(()=>{"use strict";Ve()});var Wb={};H(Wb,{WorkerLocalTma:()=>jp});var Dr,Up,Fp,Bp,jp,Vb=v(()=>{"use strict";Ve();Dp();Wn();F();W();Pt();Np();Te();$b();Pa();Dr=C("worker-appium"),Up=class extends Error{},Fp=class extends Error{},Bp=class extends Error{},jp=class extends Ot{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}=X(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await jb(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:A}=await Tt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=A}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:w,version:b},S]=await Promise.all([this.getAppStateFromDevice(o,a,T),Bb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Dr.info("device status and app state",{deviceStatus:S,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),Dr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let A={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=Ob({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),R={capabilities:{udid:a,...D}};Dr.info("requesting new appium session from TMA",{tmaSessionSettings:R,executionId:this.executionId,testResultId:this.testResultId});let N=await this.requestNewAppiumSessionFromTma(o,R,g);this.sessionData=N;let O=await m.attach({sessionId:N.sessionId,capabilities:D,options:{capabilities:D}});this.device=await Tt.updateTmaDeviceDetails(a,this.options,t),Dr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:O.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:O.capabilities})}catch(A){throw Dr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await We({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=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Bp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await be(o)).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 i,o;try{let a=await Mt(n);await Bs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Fp(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Up(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=X(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.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 i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Dr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Dr.error("failed to run test once",{err:c}),c}}}});var Hb={};H(Hb,{WorkerAppium:()=>$p});var Gb,Mr,$p,qb=v(()=>{"use strict";F();Dp();Gb=require("linkedom");Wn();W();Pt();Np();Te();Pa();ie();os();Mr=C("worker-appium"),$p=class extends Ot{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==L.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:l}=n,c=await Tt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),d=o==="android"?t.androidActivityWait:null,m=t.nativeAppMetadata;if(!m)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:o,nativeAppMetadata:m,appPath:c,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Tt.lockDevice(i,this.options.deviceUdid),h=await kb(f)):h=Pb({...f,shouldRunInEnhancedMode:a}),Mr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:_b(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await l.remote(h),this.device=await Tt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Mr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Mr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}async startKeepAlive(t){let{errors:r}=X(),n=async()=>{try{await t.getOrientation()}catch(i){Mr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&fg(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){Mr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=X(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:S}=await Tt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${S}`}else d=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,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:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Gb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Mr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await ce(u(),c)}catch(y){throw Mr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:runner-v4.142.0"}}});var Ua,zb=v(()=>{"use strict";F();Nn();Y();Ua=class{constructor(e){this.id=e;this.driver=new xr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Kb,Fa,Jb=v(()=>{"use strict";Kb=I(require("ws"));F();Fa=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 Kb.default(this._cdpUrl,{timeout:e}),r=qt(i=>{t.once("open",i)}),n=qt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),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 i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var ja,Wp,Ba,Yb=v(()=>{"use strict";F();ja=I(require("chrome-launcher"));Ju();Jb();fn();Wp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Fa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=No({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...ja.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await ja.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await mr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),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}},Ba=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new Wp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Vp={};H(Vp,{WorkerExtension:()=>Xn});function _I(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Xb(s){return _I(s)?s:new Error(s)}var ut,Xn,$a=v(()=>{"use strict";je();Y();Wn();F();W();Pt();ie();zb();Yb();it();ut=C("worker-ext"),Xn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Ba(this.id):new Ua(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.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:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Vi(),initializedFromCache:Gi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;U("WorkerExtension runTestOnce");let o=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,Me.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))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:i,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(U("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(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();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Me.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.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:i}),m.unregisterToClosedBrowser(y),T.type=Ws.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG),w=await hc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(E){ut.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.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})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),Xb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),Xb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),U("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Hp={};H(Hp,{WorkerExtensionSingleBrowser:()=>Gp});var LI,DI,Gp,qp=v(()=>{"use strict";je();F();W();pp();Pt();$a();LI=C("base-worker"),DI=500,Gp=class extends Xn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await jn(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,i){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(LI.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 i=this.handleQuarantine(t);if(i)return i;U("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ae(DI)}}});var zp,Wa,Qb=v(()=>{"use strict";Nn();de();je();ju();it();ep();Y();W();ie();zh();eo();zp=C("worker-manager"),Wa=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(Op(),kp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(Vb(),Wb))).WorkerLocalTma:(await Promise.resolve().then(()=>(qb(),Hb))).WorkerAppium;default:return Un.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(qp(),Hp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>($a(),Vp))).WorkerExtension}else switch(r){case(vr.find(n=>n===r)&&Un.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(qp(),Hp))).WorkerExtensionSingleBrowser;case vr.find(n=>n===r):return(await Promise.resolve().then(()=>($a(),Vp))).WorkerExtension;case bn.find(n=>n===r):return(await Promise.resolve().then(()=>(Op(),kp))).WorkerSelenium;default:throw new x(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return U("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{U("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var pe,_t,wt,Nr,P,M,j,K;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Go(r,n,e,i,o,t),this.combinedTestResults={};let T=((pe=i.company)==null?void 0:pe.ucid)||"",w=(_t=i.company)==null?void 0:_t.companyId,b=(wt=i.company)==null?void 0:wt.name,S=i.source||"cli",E=i.user,A=(Nr=i.company)==null?void 0:Nr.planType,D=(P=i.company)==null?void 0:P.isStartUp,R=(M=i.projectData)==null?void 0:M.name,N=(j=i.projectData)==null?void 0:j.type,O=i.lightweightMode,_=(K=i.gridData)==null?void 0:K.type,$=(Ce,vt,we,Ka,Zn,Ja)=>(d++,Cg({executionId:r,projectId:g,testId:vt,resultId:we,ucid:T,companyId:w,companyName:b,projectName:R,companyPlan:A,source:S,user:E,lightweightMode:O,isStartUp:D,projectType:N,appSource:Ja,gridType:_}),t.testStartAndReport(Ce,r,we,Ka,Zn)),V=async(Ce,vt,we,Ka,Zn,Ja)=>{var td,rd,sd;d--;let Qe={...(O==null?void 0:O.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...i.host&&{gridHost:i.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),i.grid||i.gridId?(Qe.gridName=i.grid||((td=i.gridData)==null?void 0:td.name),Qe.gridType=(rd=i.gridData)==null?void 0:rd.type,Qe.gridProvider=(sd=i.gridData)==null?void 0:sd.provider):i.localTmaUrl?(Qe.gridName="local-tma-from-options",Qe.gridType="local-tma"):i.useLocalChromeDriver?(Qe.gridName="local-chrome-driver-from-options",Qe.gridType="local-chrome"):i.useChromeLauncher?(Qe.gridName="chrome-launcher-from-options",Qe.gridType="local-chrome"):i.browserstack?Qe.gridName="browserstack-from-options":i.saucelabs&&(Qe.gridName="saucelabs-from-options"),await t.testEndAndReport(Ce,we,r,Ka,Zn,Qe).catch(xT=>zp.error("testEndAndReport threw an error",{err:xT})),Zn)return;this.combinedTestResults[we.resultId]=we,Pg({executionId:r,projectId:g,testId:vt,resultId:we.resultId,result:we,ucid:T,companyId:w,companyName:b,projectName:R,companyPlan:A,source:S,user:E,lightweightMode:O,logger:zp,isStartUp:D,projectType:N,appSource:Ja}),l&&!we.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},z=(Ce,vt)=>{this.combinedTestResults[vt.resultId]=vt,t.onTestIgnored(Ce,vt.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},ee=(Ce,vt)=>t.onGridSlot(Ce,vt);for(i.userData={loginData:{...br(),refreshToken:$i(),authData:br(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:fe},U("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,$,V,ee,z)});try{let u=await Rt(),f=await Wi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new Gt;return h}catch(u){throw zp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var Qn,Va,Kp,Ga,Zb=v(()=>{"use strict";Qn=I(require("lodash"));F();W();de();ie();je();ns();Eu();ju();ge();le();Pt();Yg();Y();Qb();eo();({CLI_MODE:Va}=Nt),Kp=C("test-plan-runner"),Ga=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Wa(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,g,y);Object.assign(c,T)},u=async()=>{let g=pi||i.parallel,y=!1;U("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);U("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};kg({executionId:o,projectId:i.project}),U("right before runBeforeTests");try{return await m(),U("right before runTestPlanTests"),await u(),U("right after runTestPlanTests"),await f(),c}catch(g){if(Kp.error("error running test plan",{err:g}),g instanceof Gt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Va.SELENIUM){let[{getSessionPlayer:S},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(Te(),Qt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=S();await A.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await _l(i.project),Qn.default.isEmpty(g)||!o))return;let{runKey:S,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:S}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,S,E;let c=re(),d=n.project;pc(c),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Do(m,n,o,a),f=Qn.default.chain(m).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);U("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),U("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return U("before executionEnd"),await u.executionEnd(c),U("after executionEnd"),{results:w,executionId:c,testPlanName:i,configName:h}}async runTestPlans(e,t){Kp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Qn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};k.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async d=>{let m=await un(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await se(e.testPlan,async d=>{let m=await un(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await un(o,e.testPlan,e.testPlanIds,t,e.intersections);let l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new x(`no test plan to run ${JSON.stringify(e.testPlan)}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new x(`no test to run in test plan ${JSON.stringify(e.testPlan)}`)}return e.mode!==Va.APPIUM&&await ru(e,r(c)),await se(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 ag(e,d);let f=u.overrideExecutionName||d.name;return await se(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:tu(n[m][E])})),w=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,A)=>Object.assign(E,A),{}),b=tu(w);Object.assign(i,w);let S=b?T[0].executionId:T.find(E=>!E.status).executionId;return await ml(o,m,{success:b,executions:T,executionId:S}),y})})}async runAnonymousTestPlan(e,t){var l;Kp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),U("before getSuite");let r=await wf(e,t);if(U("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new x("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new x("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new x("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;U("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Va.APPIUM&&(a=await pn({appId:e.appId,projectId:e.project})),await se(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!==Va.APPIUM&&await ru(e,c),U("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return U("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=Cn(),r=[];Gs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Qn.default.flattenDeep(r);return U("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),U("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}}});var sT={};H(sT,{init:()=>rR,run:()=>QI});async function MI(s){let e=s.project,t=await yl(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"),hn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ds}function UI(s,e){var i,o,a,l,c,d,m,u,f,h,g,y,T;let t=Ri(e.activePlan),r=s.parallel;if(t==="free"&&r>tT)throw new x(`The free plan allows only ${tT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let w=(i=s.projectData)!=null&&i.type?NI[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&w?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[w]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
409
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Qy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ba,Ta,tb=v(()=>{"use strict";ba=require("url");ue();Ta=class extends G{async updateBaseUrl(e){let t=new ba.URL(e),r=new ba.URL(this.context.recordedBaseUrl),n=new ba.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 wa,rb=v(()=>{"use strict";ue();F();wa=class extends G{async performAction(){await ae(this.step.durationMS||0)}}});var va,sb=v(()=>{"use strict";ue();va=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Kn,nb=v(()=>{"use strict";ue();Kn=class extends G{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.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.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}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},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Sa,ib=v(()=>{"use strict";ue();Sa=class extends G{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 ob,Ep,Ip,ab=v(()=>{"use strict";ob=I(require("@applitools/spec-driver-webdriverio"));ci();Te();Ep=class{constructor(){let{EyeSdkBuilder:e}=X(),t=ad["@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:ob.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=X(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Ip=new Ep});var lb,cb,Jn,ub=v(()=>{"use strict";lb=I(require("lodash"));ue();W();ab();cb=C("pixel-validation-step-action"),Jn=class extends G{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Ip.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"};lb.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),cb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){cb.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Ip.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,Rp=v(()=>{"use strict";gs();Y();ca();vs=class extends ir{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:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await fs(i,o,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 oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var or,pb=v(()=>{"use strict";Rp();or=class extends vs{isFailedResult(e){return e===!1}}});var Ea,db=v(()=>{"use strict";Rp();Ea=class extends vs{isFailedResult(e){return!e}}});var Ia,mb=v(()=>{"use strict";gs();ue();Y();Ia=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await ms(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Et?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Or,fb=v(()=>{"use strict";ue();Or=class extends G{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,gb=v(()=>{"use strict";ue();ye=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ra,hb=v(()=>{"use strict";ue();Ra=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));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(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Aa,yb=v(()=>{"use strict";ue();Aa=class extends G{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 oI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function xa(s,e){oI(aI,e),e.registerLocateStepActionUtils(Gn.getUtils(s))}var aI,Ap=v(()=>{"use strict";my();hy();Ry();Ay();Cy();Oy();Dy();My();Ny();Uy();jy();$y();Wy();Hy();Ky();eb();tb();rb();sb();nb();ib();ub();pb();db();mb();fb();gb();hb();yb();aI={locate:Gn,scroll:sa,mouse:na,submit:da,text:oa,"special-key":la,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":ia,"text-validation":qn,"wait-for-text-validation":qn,"select-option":pa,"drop-file":ga,"input-file":ya,hover:ma,navigation:Ta,wheel:fa,sleep:wa,refresh:va,"keyboard-shortcut-step":ua,"api-validation":Kn,"api-action":Kn,"api-code-step":Wt,"extract-text":Sa,"simple-ui-verification":Jn,"wait-for-simple-ui-verification":Jn,"cli-validation-download-file":Or,"cli-wait-for-download-file":Or,"network-validation-step":Or,"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":Ea,"node-package":Ia,"email-code-step":Wt,"cli-email-code-step":or,"sfdc-internal-test-step":Aa,"sfdc-recorded-step":Ra,"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":Or,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var bb,cI,Ss,xp=v(()=>{"use strict";bb=["simple-ui-verification","wait-for-simple-ui-verification"],cI=[...bb,"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=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=cI.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 bb.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 wb={};H(wb,{SeleniumTestPlayer:()=>Yn});var Tb,lI,Yn,Cp=v(()=>{"use strict";F();Tb=require("@applitools/eyes-sdk-core");Nn();Y();W();yp();cy();vp();ta();py();Sp();Te();Ap();xp();lI=C("SeleniumTestPlayer"),Yn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Ss(ra());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=X();this.driver=n??new xr;let d=new ea(this.driver);this.stepActionFactory=new c(d),xa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Qo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=uy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ts(this.driver),FrameLocator:m,portSelector:Zo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Tb.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=i,this.sessionPlayer.playbackManager.previousTestResultId=o,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}=X(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){lI.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(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var kp={};H(kp,{WorkerSelenium:()=>Pp});function pI(s){let{playback:e}=X().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>U(`Got event ${t}`))}var Ca,uI,Pp,Op=v(()=>{"use strict";F();je();Wn();W();Pt();oo();ie();gp();Y();Cp();Te();it();Ca=C("worker-selenium"),uI=1e9,Pp=class extends Ot{initPlayer(t){return new Yn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){U("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new bs(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),U("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),U("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,uI),await this.windowUtils.validatePageIsAvailable(),U("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 St||d||m?new St(`Page '${l}' is not available`):(Ca.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Vi(),initializedFromCache:Gi()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=X(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),pI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await wn(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,Me.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof oe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Ca.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=o.maxKeepAliveGap();f>=3e4&&(Ca.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 o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),U("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),U("right after super.runTestOnce in workerSelenium");let u=await d();return U("right after runSeleniumTest"),u}catch(u){throw Ca.error("failed to run test once",{err:u}),u}}}});var vb,Sb,Ge,dI,mI,_p,Tt,Pa=v(()=>{"use strict";vb=I(require("ora")),Sb=require("jimp");de();Ve();ge();W();ie();Te();le();Ge=C("mobile-grid-service"),dI="https://tdc.tricentis-cloud.com",mI="https://ui.headspin.io",_p=class{constructor(){this.gridsAppIdGetter={[L.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[L.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[L.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[L.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[L.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[L.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===L.TESTIM_TDC||e===L.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===L.TESTIM_HEADSPIN?`${r||rc}/${nc}/devices`:t===L.TESTIM_TDC?`${r||sc}/${nc}/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),i=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:i})}catch(o){throw Ge.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw Ge.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await js(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.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===L.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===L.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([L.BROWSERSTACK,L.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:i,gridId:o}){var a,l,c;if(t===L.TESTIM_HEADSPIN||t===L.TESTIM_TDC){let d=await Ul({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.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,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=X();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Tr(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),Ge.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=X(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await Sb.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/c.width,width:u,height:f}}catch(o){return Ge.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,i,o,a,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ls}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?mI:dI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await be(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:l}=t,c=await this.getTmaDeviceDetails(l,e);return await Tr(a,n,i,o,"RUNNING",{device:c}),Ge.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:c}),c}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(k.flags.allowFixingAppIdStructure.isEnabled()&&(Ge.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Bl({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await pn({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/(Sd*60))+1)*60*1e3,Math.max(vd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[L.BROWSERSTACK]:{name:"Browserstack"},[L.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[L.P_CLOUDY]:{name:"pCloudy"}}[i].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,vb.default)(`uploading app to ${a} please wait..`).start();try{Ge.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Fl({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}`),Ge.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:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,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){Ge.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else Ge.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===L.BROWSERSTACK||f===L.TESTIM_TVC||f===L.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(Ge.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&Ge.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}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:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Ls}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${ic}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?rc:sc}/${ic}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Ed}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&Ge.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===L.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await wc({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 be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await be(e,void 0,i)}},Tt=new _p});function Eb({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"&&!fI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function gI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==L.TESTIM_TDC&&e.type!==L.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 hI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function yI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&k.flags.enableBatchHeadSpin.isEnabled(),d=o&&(k.flags.enableBatchTDC.isEnabled()||k.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=k.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,...k.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:hI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function ka(s){return"id"in s?s.id:s.packageName}function bI(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function TI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=bI(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":ka(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":ka(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:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:ka(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:ka(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Ib({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let l=yI(o.type,i,n);return TI({projectType:s,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function _a({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 La({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===L.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?oc:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":oc:".*")}function wI(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 vI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Oa(s,Es)}}function Rb(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function SI(s){return Rb(s,e=>e.startsWith("browserstack."),"browserstack.")}function EI(s){return Rb(s,e=>!e.startsWith("browserstack."))}function Ab(s){return!s||!xb(s)?"2.0.0":s}function xb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Cb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=xb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Oa(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}function II({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:l}){let{osVersion:c,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=wI(i,s),h=_a({osVersion:c,mobileConfig:m}),g=La({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),y=He(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),T={device:g,os_version:h,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":y,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Lr({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:l})}function RI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=k.flags.enableAppium2pCloudy.isEnabled(),g=_a({osVersion:l,mobileConfig:d}),y=La({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),w={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...w,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Id),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=vI(b)),t="",Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Es}})}function AI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=_a({osVersion:l,mobileConfig:d}),f=La({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,_r.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Cb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},w={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:Ab(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...Oa(h,Es),"sauce:options":{...T,...w,...(0,_r.omit)(g,"appiumVersion")}};return Lr({projectType:s,sessionCaps:b,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=_a({osVersion:l,mobileConfig:d}),f=La({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=SI(n.browserstack),g=(0,_r.omit)(EI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:w}=n.browserstack||{},b=k.flags.enableAppium2BrowserStack.isEnabled();if(b||Cb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":Ab(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},A={"appium:platformVersion":u,"appium:deviceName":f,...Oa(g,Es),"bstack:options":{...E,...(0,_r.omit)(h,"appiumVersion")}};return Lr({projectType:s,sessionCaps:A,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let S={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:w||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Oa(h,"browserstack.")};return Lr({projectType:s,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Ib(s);if(L.TESTIM_TVC===s.gridInfo.type)return II(s);if(L.P_CLOUDY===s.gridInfo.type)return RI(s);if(L.SAUCELABS===s.gridInfo.type)return AI(s);if(L.BROWSERSTACK===s.gridInfo.type)return xI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function PI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((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),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Pb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);Eb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=Tt.getGridConnection(e),l=CI(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=PI(r,i==null?void 0:i.mobile);if(!(0,_r.isEmpty)(T)){let w=Object.entries(T).map(([b,S])=>S.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=w}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=k.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Lp.default)("2m"),f=(0,Lp.default)("12m"),h=pr(k.flags.appiumConnectionRetryCount.getValue(),m),g=pr(k.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function kb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Eb({nativeAppMetadata:r,appPath:i,gridInfo:t}),gI({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 Tt.getGridDirectConnection(t,d),f=Ib({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,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 Ob(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Lr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function _b(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 Lp,_r,Es,fI,Dp=v(()=>{"use strict";Lp=I(require("ms"));le();ie();Pa();_r=require("lodash");F();de();Es="appium:",fI=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var Da,Db=v(()=>{"use strict";Da=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 Ma,Mb=v(()=>{"use strict";F();Ma=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 Mp,Na,Nb=v(()=>{"use strict";W();Mp=C("mobile-frame-locator-mock"),Na=class{foundFrameCallback(){return Mp.info("foundFrameCallback-mock invoked"),{}}locate(){return Mp.info("locate-mock invoked"),{}}async findFrame(){return Mp.info("findFrame-mock invoked"),{}}}});var kI,Fb,Ub,Is,Np=v(()=>{"use strict";kI=I(require("webdriverio")),Fb=require("@applitools/eyes-sdk-core");Db();vp();W();Mb();Sp();Te();Ap();Nb();xp();Ub=C("appium-test-player"),Is=class{constructor(e,t,r,n=kI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=X(),m=new Ma(this.driver);this.stepActionFactory=new c(m),xa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ss(ra()),this.sessionPlayer=new a(e,{tabService:new Da,cookieUtils:void 0,FrameLocator:Na,portSelector:Zo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Fb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,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,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Ub.info("appium session deleted",{...i}))}catch(o){Ub.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=X();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function OI(s){return await be(`${s}/api/status`)}async function Bb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function jb(s){if((await OI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var $b=v(()=>{"use strict";Ve()});var Wb={};H(Wb,{WorkerLocalTma:()=>jp});var Dr,Up,Fp,Bp,jp,Vb=v(()=>{"use strict";Ve();Dp();Wn();F();W();Pt();Np();Te();$b();Pa();Dr=C("worker-appium"),Up=class extends Error{},Fp=class extends Error{},Bp=class extends Error{},jp=class extends Ot{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}=X(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await jb(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:A}=await Tt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=A}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:w,version:b},S]=await Promise.all([this.getAppStateFromDevice(o,a,T),Bb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Dr.info("device status and app state",{deviceStatus:S,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),Dr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let A={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=Ob({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),R={capabilities:{udid:a,...D}};Dr.info("requesting new appium session from TMA",{tmaSessionSettings:R,executionId:this.executionId,testResultId:this.testResultId});let N=await this.requestNewAppiumSessionFromTma(o,R,g);this.sessionData=N;let O=await m.attach({sessionId:N.sessionId,capabilities:D,options:{capabilities:D}});this.device=await Tt.updateTmaDeviceDetails(a,this.options,t),Dr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:O.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:O.capabilities})}catch(A){throw Dr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await We({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=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Bp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await be(o)).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 i,o;try{let a=await Mt(n);await Bs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Fp(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Up(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=X(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.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 i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Dr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Dr.error("failed to run test once",{err:c}),c}}}});var Hb={};H(Hb,{WorkerAppium:()=>$p});var Gb,Mr,$p,qb=v(()=>{"use strict";F();Dp();Gb=require("linkedom");Wn();W();Pt();Np();Te();Pa();ie();os();Mr=C("worker-appium"),$p=class extends Ot{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==L.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:l}=n,c=await Tt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),d=o==="android"?t.androidActivityWait:null,m=t.nativeAppMetadata;if(!m)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:o,nativeAppMetadata:m,appPath:c,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Tt.lockDevice(i,this.options.deviceUdid),h=await kb(f)):h=Pb({...f,shouldRunInEnhancedMode:a}),Mr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:_b(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await l.remote(h),this.device=await Tt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Mr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Mr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}async startKeepAlive(t){let{errors:r}=X(),n=async()=>{try{await t.getOrientation()}catch(i){Mr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&fg(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){Mr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=X(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:S}=await Tt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${S}`}else d=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,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:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Gb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Mr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await ce(u(),c)}catch(y){throw Mr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:runner-v4.142.2"}}});var Ua,zb=v(()=>{"use strict";F();Nn();Y();Ua=class{constructor(e){this.id=e;this.driver=new xr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Kb,Fa,Jb=v(()=>{"use strict";Kb=I(require("ws"));F();Fa=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 Kb.default(this._cdpUrl,{timeout:e}),r=qt(i=>{t.once("open",i)}),n=qt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),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 i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var ja,Wp,Ba,Yb=v(()=>{"use strict";F();ja=I(require("chrome-launcher"));Ju();Jb();fn();Wp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Fa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=No({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...ja.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await ja.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await mr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),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}},Ba=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new Wp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Vp={};H(Vp,{WorkerExtension:()=>Xn});function _I(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Xb(s){return _I(s)?s:new Error(s)}var ut,Xn,$a=v(()=>{"use strict";je();Y();Wn();F();W();Pt();ie();zb();Yb();it();ut=C("worker-ext"),Xn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Ba(this.id):new Ua(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.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:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Vi(),initializedFromCache:Gi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;U("WorkerExtension runTestOnce");let o=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,Me.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))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:i,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(U("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(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();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Me.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.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:i}),m.unregisterToClosedBrowser(y),T.type=Ws.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG),w=await hc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(E){ut.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.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})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),Xb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),Xb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),U("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Hp={};H(Hp,{WorkerExtensionSingleBrowser:()=>Gp});var LI,DI,Gp,qp=v(()=>{"use strict";je();F();W();pp();Pt();$a();LI=C("base-worker"),DI=500,Gp=class extends Xn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await jn(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,i){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(LI.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 i=this.handleQuarantine(t);if(i)return i;U("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ae(DI)}}});var zp,Wa,Qb=v(()=>{"use strict";Nn();de();je();ju();it();ep();Y();W();ie();zh();eo();zp=C("worker-manager"),Wa=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(Op(),kp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(Vb(),Wb))).WorkerLocalTma:(await Promise.resolve().then(()=>(qb(),Hb))).WorkerAppium;default:return Un.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(qp(),Hp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>($a(),Vp))).WorkerExtension}else switch(r){case(vr.find(n=>n===r)&&Un.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(qp(),Hp))).WorkerExtensionSingleBrowser;case vr.find(n=>n===r):return(await Promise.resolve().then(()=>($a(),Vp))).WorkerExtension;case bn.find(n=>n===r):return(await Promise.resolve().then(()=>(Op(),kp))).WorkerSelenium;default:throw new x(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return U("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{U("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var pe,_t,wt,Nr,P,M,j,K;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Go(r,n,e,i,o,t),this.combinedTestResults={};let T=((pe=i.company)==null?void 0:pe.ucid)||"",w=(_t=i.company)==null?void 0:_t.companyId,b=(wt=i.company)==null?void 0:wt.name,S=i.source||"cli",E=i.user,A=(Nr=i.company)==null?void 0:Nr.planType,D=(P=i.company)==null?void 0:P.isStartUp,R=(M=i.projectData)==null?void 0:M.name,N=(j=i.projectData)==null?void 0:j.type,O=i.lightweightMode,_=(K=i.gridData)==null?void 0:K.type,$=(Ce,vt,we,Ka,Zn,Ja)=>(d++,Cg({executionId:r,projectId:g,testId:vt,resultId:we,ucid:T,companyId:w,companyName:b,projectName:R,companyPlan:A,source:S,user:E,lightweightMode:O,isStartUp:D,projectType:N,appSource:Ja,gridType:_}),t.testStartAndReport(Ce,r,we,Ka,Zn)),V=async(Ce,vt,we,Ka,Zn,Ja)=>{var td,rd,sd;d--;let Qe={...(O==null?void 0:O.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...i.host&&{gridHost:i.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),i.grid||i.gridId?(Qe.gridName=i.grid||((td=i.gridData)==null?void 0:td.name),Qe.gridType=(rd=i.gridData)==null?void 0:rd.type,Qe.gridProvider=(sd=i.gridData)==null?void 0:sd.provider):i.localTmaUrl?(Qe.gridName="local-tma-from-options",Qe.gridType="local-tma"):i.useLocalChromeDriver?(Qe.gridName="local-chrome-driver-from-options",Qe.gridType="local-chrome"):i.useChromeLauncher?(Qe.gridName="chrome-launcher-from-options",Qe.gridType="local-chrome"):i.browserstack?Qe.gridName="browserstack-from-options":i.saucelabs&&(Qe.gridName="saucelabs-from-options"),await t.testEndAndReport(Ce,we,r,Ka,Zn,Qe).catch(xT=>zp.error("testEndAndReport threw an error",{err:xT})),Zn)return;this.combinedTestResults[we.resultId]=we,Pg({executionId:r,projectId:g,testId:vt,resultId:we.resultId,result:we,ucid:T,companyId:w,companyName:b,projectName:R,companyPlan:A,source:S,user:E,lightweightMode:O,logger:zp,isStartUp:D,projectType:N,appSource:Ja}),l&&!we.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},z=(Ce,vt)=>{this.combinedTestResults[vt.resultId]=vt,t.onTestIgnored(Ce,vt.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},ee=(Ce,vt)=>t.onGridSlot(Ce,vt);for(i.userData={loginData:{...br(),refreshToken:$i(),authData:br(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:fe},U("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,$,V,ee,z)});try{let u=await Rt(),f=await Wi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new Gt;return h}catch(u){throw zp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var Qn,Va,Kp,Ga,Zb=v(()=>{"use strict";Qn=I(require("lodash"));F();W();de();ie();je();ns();Eu();ju();ge();le();Pt();Yg();Y();Qb();eo();({CLI_MODE:Va}=Nt),Kp=C("test-plan-runner"),Ga=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Wa(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,g,y);Object.assign(c,T)},u=async()=>{let g=pi||i.parallel,y=!1;U("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);U("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};kg({executionId:o,projectId:i.project}),U("right before runBeforeTests");try{return await m(),U("right before runTestPlanTests"),await u(),U("right after runTestPlanTests"),await f(),c}catch(g){if(Kp.error("error running test plan",{err:g}),g instanceof Gt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Va.SELENIUM){let[{getSessionPlayer:S},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(Te(),Qt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=S();await A.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await _l(i.project),Qn.default.isEmpty(g)||!o))return;let{runKey:S,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:S}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,S,E;let c=re(),d=n.project;pc(c),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Do(m,n,o,a),f=Qn.default.chain(m).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);U("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),U("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return U("before executionEnd"),await u.executionEnd(c),U("after executionEnd"),{results:w,executionId:c,testPlanName:i,configName:h}}async runTestPlans(e,t){Kp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Qn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};k.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async d=>{let m=await un(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await se(e.testPlan,async d=>{let m=await un(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await un(o,e.testPlan,e.testPlanIds,t,e.intersections);let l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new x(`no test plan to run ${JSON.stringify(e.testPlan)}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new x(`no test to run in test plan ${JSON.stringify(e.testPlan)}`)}return e.mode!==Va.APPIUM&&await ru(e,r(c)),await se(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 ag(e,d);let f=u.overrideExecutionName||d.name;return await se(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:tu(n[m][E])})),w=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,A)=>Object.assign(E,A),{}),b=tu(w);Object.assign(i,w);let S=b?T[0].executionId:T.find(E=>!E.status).executionId;return await ml(o,m,{success:b,executions:T,executionId:S}),y})})}async runAnonymousTestPlan(e,t){var l;Kp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),U("before getSuite");let r=await wf(e,t);if(U("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new x("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new x("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new x("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;U("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Va.APPIUM&&(a=await pn({appId:e.appId,projectId:e.project})),await se(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!==Va.APPIUM&&await ru(e,c),U("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return U("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=Cn(),r=[];Gs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Qn.default.flattenDeep(r);return U("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),U("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}}});var sT={};H(sT,{init:()=>rR,run:()=>QI});async function MI(s){let e=s.project,t=await yl(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"),hn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ds}function UI(s,e){var i,o,a,l,c,d,m,u,f,h,g,y,T;let t=Ri(e.activePlan),r=s.parallel;if(t==="free"&&r>tT)throw new x(`The free plan allows only ${tT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let w=(i=s.projectData)!=null&&i.type?NI[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&w?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[w]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
410
410
  We'll use the maximum of ${b} for now. To use more, you can adjust your command or upgrade your plan.`),s.parallel=b);let S=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.tunnel;if(s.tunnel&&!S)throw new x("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 E=(m=(d=e.activePlan)==null?void 0:d.premiumFeatures)==null?void 0:m.runInTurboMode;s.lightweightMode&&!E&&(console.warn(`
411
411
  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&&((u=s.gridData)==null?void 0:u.type)===L.TESTIM_TVC){let w=e.tvcLicense.expireAt||1;if(Date.now()>w&&!e.churnedByL2C)throw new x("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let b=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>b)throw new x(`Your license allows only ${b} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((g=s.gridData)==null?void 0:g.type)===L.TESTIM_TDC){let w=e.tdcLicense.expireAt||1;if(Date.now()>w)throw new x("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){let w=(T=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:T.resultRetention;if(n>w)throw new x(`Retention days (${n}) cannot be greater than the company's retention days (${w}). Run aborted`)}if(zt(s)){if(k.flags.removeMobileTrialRestrictions.isEnabled())return;let w=e.tvcLicense,b=e.tdcLicense;if(w!=null&&w.isPaid||b!=null&&b.isPaid)return;let S=e==null?void 0:e.createdAt;if(new Date(S)<new Date(k.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let A=s.retries;A&&A>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function FI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await MI(s)}catch(t){if([x,Ds].some(r=>t instanceof r))throw t;Jp.error("could not validate cli account",{err:t})}}function BI(s){let e=br();return mf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function jI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(k.flags.useNewWSCLI.isEnabled()&&!e&&!t)return yt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>($o(),Uh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Wo(),jh));r.init(s)}}function $I(s,e){let{branch:t,autoDetect:r}=s;if(gg(e,r),!e&&!r)throw new x(`branch ${t} does not exist, run aborted.`)}async function WI(s,e){let{id:t,type:r}=e,i=rT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&k.flags.sfdcHybridCompany.isEnabled(),o=Cn();i&&(s.sfdcCredential=await dl({projectId:t,branch:o}))}function VI(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=Ri(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<eT?eT:s.newBrowserWaitTimeout),k.setCompanyId(t),k.setIsPOC(i),k.setIsStartUp(o),k.setPlanType(a),Ct.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function GI(s,e){s.editorUrl=Os||e.editorUrl}function HI(s,e){s.allGrids=e}function qI(s,e){s.authData=e}function zI(s,e){let{id:t,name:r,type:n,defaults:i}=e;k.setProjectId(t),k.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function KI(s){var e;s.gridData=await cg(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function JI(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function YI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(gt("user-override-file",t),s.mockNetworkRules=await ef(s.overrideMappingFile))}async function XI(s,e){U("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await FI(s),U("in runRunner before tunnel.connect"),await fo(s),U("in runRunner after tunnel.connect");let a=await new Ga(e).run(s);return U("before tunnel.disconnect"),await go(s),await tR(s.slotService,t,s.company.companyId),U("after tunnel.disconnect and gridService.keepAlive.end"),a}function ZI(s){var e;Ct.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
412
412
  \x1B[4m\x1B[36mOur Free grid offers basic service performance.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@testim/testim-cli",
3
- "version": "4.142.0",
3
+ "version": "4.142.2",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@testim/testim-cli",
9
- "version": "4.142.0",
9
+ "version": "4.142.2",
10
10
  "license": "Proprietary",
11
11
  "dependencies": {
12
12
  "@applitools/eyes-sdk-core": "13.11.34-legacy.1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@testim/testim-cli",
3
- "version": "4.142.0",
3
+ "version": "4.142.2",
4
4
  "description": "Command line interface for running Testing on your CI",
5
5
  "author": "Oren Rubin",
6
6
  "contributors": [