@testim/testim-cli 4.183.4 → 4.183.5

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,47 +1,47 @@
1
1
  #! /usr/bin/env node
2
- "use strict";var Iw=Object.create;var vi=Object.defineProperty;var Rw=Object.getOwnPropertyDescriptor;var xw=Object.getOwnPropertyNames;var Cw=Object.getPrototypeOf,Aw=Object.prototype.hasOwnProperty;var I=(s,e)=>()=>(s&&(e=s(s=0)),e);var z=(s,e)=>{for(var t in e)vi(s,t,{get:e[t],enumerable:!0})},Bd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xw(e))!Aw.call(s,n)&&n!==t&&vi(s,n,{get:()=>e[n],enumerable:!(r=Rw(e,n))||r.enumerable});return s};var R=(s,e,t)=>(t=s!=null?Iw(Cw(s)):{},Bd(e||!s||!s.__esModule?vi(t,"default",{value:s,enumerable:!0}):t,s)),Je=s=>Bd(vi({},"__esModule",{value:!0}),s);var We={};z(We,{log:()=>M,measure:()=>kw});function M(...s){if(!$d)return;let e=Date.now();console.log(`${e-Pw} ${e-jd} `,...s),jd=e}function kw(s,e){if(!$d)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var $d,Pw,jd,Ve=I(()=>{"use strict";$d=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,Pw=Date.now(),jd=Date.now()});var er,Kr=I(()=>{"use strict";er="element-6066-11e4-a52e-4f735466cecf"});function ne(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 Xe(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 vc(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function Me(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 Sc=I(()=>{"use strict"});var Ic,Wd,Vd,Pi=I(()=>{Ic={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:"2.0.1"},Wd={"@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.4",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.8.1",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6","form-data":"^4.0.4",express:"4.22.1",fkill:"7.2.1","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jsonwebtoken:"9.0.3",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2","node-fetch":"2.7.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":"5.4.12",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",uuid:"11.0.5","validate-npm-package-name":"3.0.0",webdriverio:"8.44.1",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},Vd={node:">= 18.0.0"}});var wr,vr,Gd,Xs,Lw,tr,Hd,qd,ki,ot,zd,be,Kd,Jd,Oi,Ge,Rc,Xd,_i,Yd,Qd,Ex,Ix,Zd,em,tm,rm,xc,sm,Cc,nm,Ys,Qs,le=I(()=>{"use strict";wr=process.env.SERVICES_HOST||"https://services.testim.io",vr="https://app.testim.io";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:wr,wr=process.env.SERVICES_HOST);Gd=process.env.TESTIM_REGION||"us-west-2",Xs=process.env.RUNNER_ENVIRONMENT||"production",Lw={production:"",staging:".staging",development:".dev"},tr=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${Lw[Xs]||""}.testim.io`,Hd=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),qd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),ki=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),ot=process.env.EDITOR_URL,zd=process.env.WEBSOCKET_HOST||`${wr}/ws`,be=()=>wr,Kd=parseInt(process.env.LOGGER_CONSOLE||"0",10),Jd=parseInt(process.env.LOGGER_DEBUG||"0",10),Oi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),Ge=parseInt(process.env.IS_ON_PREM||"0",10),Rc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Xd=parseInt(process.env.DEBUG_MODE||"0",10),_i=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Yd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",Qd=process.env.CORALOGIX_PRIVATE_KEY||"d0eb01da-f966-1663-63c6-8871225d7c39",Ex=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),Ix=process.env.APPIUM_VERSION||"1.10.1",Zd=process.env.GATEWAY_URL,em=()=>process.env.EXTENSION_SERVICES_HOST||wr,tm=5*60*1e3,rm=40,xc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",sm=process.env.TDC_DEVICES_API_PATH||"v0",Cc=process.env.TDC_APPS_API_PATH||"v1",nm=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Ys=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Qs=s=>{wr=s,process.env.SERVICES_HOST=s,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:wr}});var im,Li,om=I(()=>{"use strict";im=R(require("superagent"));le();Li=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=Qd,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=im.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 cm={};z(cm,{CoralogixTransport:()=>Ac});var am,Dw,Nw,Ac,lm=I(()=>{"use strict";am=R(require("winston-transport"));om();Dw={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},Nw=["err","error","reason","e"],Ac=class extends am.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new Li({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...c}=t,l={...a,...c},d={severity:Dw[i],text:o,category:n||this.category};l.className&&(d.className=l.className),l.methodName&&(d.methodName=l.methodName),l.threadId&&(d.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let m=!1;a instanceof Error&&(m=!0,l.msg=a.message+a.stack,o&&(l.msg=`${o}
3
- ${l.msg}`));for(let u of Nw)a[u]instanceof Error&&(l[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(l).length>0&&(o&&!m&&(l.msg=o),d.text=JSON.stringify(l)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function Uw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!Ge){let{CoralogixTransport:r}=(lm(),Je(cm)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(Kd){let r={depth:5,colors:!0};s.push(new bt.transports.Console({format:bt.format.combine(bt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),bt.format.timestamp({format:"HH:mm:ss:SSS"}),bt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ni.inspect(n.meta,r)}`))}))}return[s,e,t]}function hm(s){Pc=s}function ym(s){gm=s}function bm(s){Ge||!s||$w(s)}function pm(s){return{projectId:gm,time:new Date().toISOString(),region:Gt.getRegion(),...Pc&&!s&&{executionId:Pc}}}function A(s){return new Gt(Gw.child({category:s}))}var dm,bt,Ni,Di,mm,Mw,Fw,um,fm,Bw,jw,$w,Ww,Vw,Gw,Pc,gm,Gt,W=I(()=>{"use strict";dm=R(require("node:os")),bt=R(require("winston"));le();Ni=R(require("node:util"));F();Di=R(require("chalk")),mm=R(require("dayjs"));F();Mw=dm.hostname(),Fw=at();um={depth:5,colors:!0},fm=(s,e,t)=>{let r=`[${(0,mm.default)().format("HH:mm:ss:SSS")}]`,n=Ni.inspect(e,um),i=Ni.inspect(t,um);return`${Di.default.white(r)} ${Di.default.reset()}SessionPlayer-${Di.default.red(s)} ${n} ${i}`},[Bw,jw,$w]=Uw(),Ww=Jd?"debug":"info",Vw={release:Boolean(!1),branch:"test"},Gw=bt.createLogger({levels:bt.config.syslog.levels,level:Ww,transports:Bw,defaultMeta:{name:"runner",hostname:Mw,nodeVersion:process.version,runnerVersion:Fw,...Vw}}),Pc=null,gm=null;Gt=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)}static setRegion(e){Gt.region=e}static getRegion(){return Gt.region}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;r.user&&(r.user=kc(r.user,["email"]));try{this._logger.log(e,{meta:r,message:t,...pm(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...pm(n)})}catch{}}}waitForFlush(){return jw()}}});var Bi,Jr,x,rr,Sr,Dt,Mi,Xr,ue,Zs,ct,sr,Nt,Fi,Yr,Ui,en,Q=I(()=>{"use strict";Bi=require("p-retry"),Jr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},x=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},rr=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},Sr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},Dt=class extends Bi.AbortError{},Mi=class extends Bi.AbortError{},Xr=class extends Bi.AbortError{},ue=class extends Error{},Zs=class extends Error{},ct=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},sr=class extends ct{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Nt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Fi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Yr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Ui=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},en=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Oc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ie(s){return(0,vm.setTimeout)(s)}function _c(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function pe(s,e,t="Timeout Error"){ki&&!Tm&&(Tm=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ue(t);return e=ki?Number(ki)||6e5:e,Promise.race([s,ie(e).then(()=>{throw r})])}async function oe(s,e,{concurrency:t}={}){if(t){wm||=(await import("p-limit")).default;let r=wm(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function nr(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var vm,Tm,wm,Lc=I(()=>{"use strict";vm=require("timers/promises");Q();le();Tm=!1});var rn,Sm,qw,tn,Em,zw,Kw,Im,Rm=I(()=>{"use strict";rn=R(require("lodash"));le();Sm=require("dns");W();Lc();qw=A("http-request-counters"),tn=!1,Em=async()=>{if(Ge)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await oe(s,t=>Sm.promises.lookup(t)));return e||(tn=!0),e}catch{return qw.error("network connectivity test failed"),tn=!0,!1}},zw=rn.throttle(Em,10*1e3),Kw=60*1e3*15,Im=()=>{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)},Kw)}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),tn||zw(),a}}}async function r(){if(tn||!await Em())return!1;let n=rn.sum([...s.fail.values()]),i=rn.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>tn,t}});var Ye={};z(Ye,{deleteReq:()=>sn,didNetworkConnectivityTestFail:()=>jc,download:()=>Uc,get:()=>ve,getFullRes:()=>ev,getText:()=>Mc,head:()=>tv,isNetworkHealthy:()=>Bc,post:()=>He,postForm:()=>nn,postText:()=>Zw,put:()=>Fc});function Xw(){return global.caFileContent}function Yw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function Qw(){return!("proxy"in Tt.default.Request.prototype)&&global.SuperagentProxy&&global.SuperagentProxy(Tt.default),global.proxyUri}function Er(s,e=!1){let t=Xw();t&&s.ca(t);let r=!e&&Qw();r&&s.proxy(r)}async function xm(s,e,t={},r=Qr,n=0){let i=Tt.default.post(s).send(e).timeout(r).set(t);Er(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Nc(s,e,t={},r=Qr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=Tt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),Er(o,i),await o}var Tt,Dc,lt,Qr,Jw,Ht,sn,He,nn,Mc,Zw,ve,ev,tv,Fc,Uc,Bc,jc,qe=I(()=>{"use strict";Tt=R(require("superagent"));W();Rm();Dc=A("http-request"),lt=Im(),Qr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,Jw=6e4;Ht=(s,e,t)=>{let r=e.response;e.response instanceof Tt.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 Dc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};sn=lt(async(s,e={},t={},r=Qr)=>{try{let n=Tt.default.delete(s).send(e).timeout(r).set(t);Er(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Ht("failed to delete request",n,{url:s})}}),He=lt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await xm(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Ht("failed to post request",i,{url:s})}});nn=lt(async(s,e,t,r={},n=Qr)=>{let i=Tt.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)}),Er(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Ht("failed to post request",o,{url:s})}});Mc=lt(async(s,e,t)=>{try{return(await Nc(s,e,t)).text}catch(r){return Ht("failed to getText request",r,{url:s,query:e})}}),Zw=lt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await xm(s,e,t,r,n)).text}catch(i){return Ht("failed to post request",i,{url:s})}}),ve=lt(async(s,e,t,r,n)=>{try{return(await Nc(s,e,t,r,n)).body}catch(i){return Ht("failed to get request",i,{url:s,query:e})}}),ev=lt((s,e,t,r)=>Nc(s,e,t,r)),tv=lt(async s=>{let e=Tt.default.head(s).timeout(Qr);Er(e);try{return await e}catch(t){return Ht("failed to head request",t,{url:s})}}),Fc=lt(async(s,e,t={},r=Qr)=>{let n=Tt.default.put(s).send(e).timeout(r).set(t);Er(n);try{return(await n).body}catch(i){return Ht("failed to put request",i,{url:s})}}),Uc=lt(async s=>{Dc.info("start to download",{url:s});let e=Tt.default.get(s).set("User-Agent","Testim.io").timeout(Jw).buffer(!0).parse(Yw);Er(e);try{let t=await e;return Dc.info("finished to download",{url:s}),t}catch(t){return Ht("failed to download",t,{url:s})}}),Bc=lt.isNetworkHealthy,jc=lt.didNetworkConnectivityTestFail});function wt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=qt.resolve(__dirname,"../../"):s=qt.resolve(__dirname,""),s):process.cwd()}function ji(s,e){return Me(s)?e||qt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||qt.basename(s)}function at(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Hc(){try{return Vd.node}catch{return""}}async function Om(s,e,t=!0){let r=await ut.promises.readdir(s,{withFileTypes:!0});await ut.promises.mkdir(e,{recursive:t});for(let n of r){let i=qt.join(s,n.name),o=qt.join(e,n.name);n.isDirectory()?await Om(i,o):await ut.promises.copyFile(i,o)}}async function Te(s){try{return await ut.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var qt,Cm,Am,Pm,$c,km,ut,rv,zt,Qe,$i,Wc,Ze,Vc,Gc,qc,zc=I(()=>{"use strict";qt=R(require("node:path")),Cm=R(require("node:child_process"));Sc();Pi();Am=R(require("unzip-stream")),Pm=R(require("p-retry")),$c=R(require("node:fs")),km=R(require("node:crypto")),ut=require("node:fs"),rv=3;zt=async s=>{let e=await Promise.resolve().then(()=>(qe(),Ye));return(0,Pm.default)(()=>e.download(s),{retries:rv,factor:1})},Qe=async(s,e)=>{let t=await zt(s);return ut.promises.writeFile(e,t.body)};$i=async(s,e)=>{let t=ji(s,e);return Me(s)?Qe(s,t):ut.promises.copyFile(s,t)},Wc=async s=>Me(s)?zt(s):ut.promises.readFile(s),Ze=async(s,e)=>(0,ut.createReadStream)(s).pipe(Am.Extract({path:e})),Vc=(s,e)=>new Promise((t,r)=>{var o;let n=Cm.spawn("tar",["-xzf",s,"-C",e],{stdio:["ignore","pipe","pipe"]}),i="";(o=n.stderr)==null||o.on("data",a=>{i+=a.toString()}),n.on("error",a=>{r(new Error(`Failed to extract tgz file ${s}: ${a.message}. ${i}`))}),n.on("close",a=>{a!==0&&r(new Error(`Failed to extract tgz file ${s}: tar exited with code ${a}. ${i}`)),t()})}),Gc=s=>(0,ut.statSync)(s).size/1e6;qc=async(s,e,t="sha256",r="hex")=>{let n=await $c.promises.readFile(s),i=km.createHash(t).update(n).digest(r);if(i!==e)throw await $c.promises.unlink(s),new Error(`Checksum mismatch for ${s}. Expected ${e}, got ${i}`)}});var Kt={};z(Kt,{APPIUM_SESSION_MESSAGE:()=>Qc,CLI_MODE:()=>J,MOBILE_APP_SOURCE:()=>Wi,MOBILE_RUN_SKIP_REASON:()=>Yc,OPERANDS:()=>an,REGION_CONFIG:()=>es,SEGMENT_CONFIG:()=>ts,X_HEADER_RUNNER_ID:()=>Zc,gridMessages:()=>vt,gridTypes:()=>N,mobileWeb:()=>Jc,runnerStatus:()=>Kc,runnerTestStatus:()=>he,socketEventTypes:()=>Mt,stepResult:()=>Zr,test:()=>Xc,testRunStatus:()=>on,testStatus:()=>et,timeoutMessages:()=>Pe});var Pe,on,Kc,he,et,vt,Jc,Xc,Mt,J,N,Zr,Wi,Yc,Qc,Zc,es,ts,an,ae=I(()=>{"use strict";Pe={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout",TEST_REACHED_CUSTOM_TIMEOUT_MSG:"test-reached-custom-timeout"},on={COMPLETED:"completed"},Kc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},he={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},et={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},vt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Jc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Xc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Mt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},J={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},N={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC"},Zr={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",KEEP_ALIVE_FAILED:"keep-alive-failed"},Wi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Yc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Qc={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"},Zc="X-Testim-Runner-ID",es={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"},ts={TTL:1e3*60*60*72,CACHE_FN_NAME:"setSegmentConfig"},an=(t=>(t.AND="AND",t.OR="OR",t))(an||{})});function cn(s,e){var t,r,n,i,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(n=s.browser)==null?void 0:n.toLowerCase()]:(i=s.testConfigNames)!=null&&i.length||(o=s.testConfigIds)!=null&&o.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(c=>{var l;return(l=c.runConfig)==null?void 0:l.browserValue}))]:[(a=s.browser)==null?void 0:a.toLowerCase()]}function sv(){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 ln,_m,tt,nv,iv,ov,av,cv,el,tl,Lm=I(()=>{"use strict";ae();ln=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},_m=s=>Boolean(s.resultId&&s.source==="remote-run"),tt=(s,e)=>s.testStatus===et.QUARANTINE&&!_m(e)&&!e.runQuarantinedTests;nv=s=>Boolean(s.loginMode),iv=s=>Boolean(s.tunnelOnlyMode),ov=s=>Boolean(s.createPrefechedData),av=s=>Boolean(s.installLazyDepsMode),cv=s=>Boolean(s.agentMode),el=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},tl=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Gi(s=0){return Vi.default.duration(s).format("HH:mm:ss.SSS")}function rl(s=0){return Vi.default.duration(s).asSeconds()}var Vi,Dm,Hi,Nm=I(()=>{"use strict";Vi=R(require("dayjs")),Dm=R(require("dayjs/plugin/duration"));Vi.default.extend(Dm.default);Hi=s=>{let e=Math.floor(s.asMinutes()),t=s.asSeconds()%60||0;return e>0?`${e} min ${Math.floor(t)} sec`:`${Math.floor(t)} sec`}});var un,rs,ir,Mm,ss,Fm=I(()=>{"use strict";ae();un=s=>!(!s||"fileName"in s),rs=(s,e)=>{if(e===N.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},ir=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Mm=s=>s===N.TESTIM_TVC,ss=(s,e)=>Mm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function sl(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 Um=I(()=>{"use strict"});function jm(s){let e=(0,Bm.default)(s);return e.validForNewPackages||e.validForOldPackages}function nl(s){let e=s.filter(t=>!jm(t.packageName)).map(t=>t.packageName);return e.length>0?e:null}function il(s){let e=s.filter(t=>t&&(t.includes("../")||t.includes("..\\"))).map(t=>t);return e.length>0?e:null}var Bm,ol=I(()=>{"use strict";Bm=R(require("validate-npm-package-name"))});var X={};z(X,{OSS:()=>ns,TESTIM_BROWSER_DIR:()=>St,buildBasicHeader:()=>vc,calcPercentile:()=>Ki,copyDir:()=>Om,delay:()=>ie,doesPathExist:()=>Te,download:()=>zt,downloadAndSave:()=>Qe,extractElementId:()=>Fe,extractTgz:()=>Vc,formatTimeoutDuration:()=>Hi,getArgsOnRemoteRunFailure:()=>sv,getBrowserInfo:()=>uv,getCdpAddressForHost:()=>xr,getCliLocation:()=>wt,getDuration:()=>Gi,getDurationSec:()=>rl,getEnginesVersion:()=>Hc,getEnvironmentGitBranch:()=>Rr,getInvalidPackageNames:()=>nl,getInvalidPackagePaths:()=>il,getLinksFromUnescapeHTML:()=>mn,getLocalFileSizeInMB:()=>Gc,getMemorySnapshot:()=>sl,getPlanType:()=>zi,getRunConfigByBrowserName:()=>pn,getRunnerVersion:()=>at,getSource:()=>$i,getSourceAsBuffer:()=>Wc,getSourcePath:()=>ji,getTestUrl:()=>Xe,getUniqBrowsers:()=>cn,groupTestsByRetries:()=>cl,guid:()=>ne,hasTestPlanFlag:()=>ln,isAgentMode:()=>cv,isAppFromDevice:()=>un,isAppFromDeviceDisabled:()=>ss,isCreatePrefetchedDataMode:()=>ov,isInstallLazyDepsMode:()=>av,isLoginMode:()=>nv,isMobileProject:()=>ir,isPromise:()=>Oc,isQuarantineAndNotRemoteRun:()=>tt,isRemoteRun:()=>_m,isTestimVirtualGrid:()=>Mm,isTunnelOnlyMode:()=>iv,isURL:()=>Me,isValidPackageName:()=>jm,maskObjectFields:()=>kc,maskSecret:()=>qm,promiseAbort:()=>_c,promiseFromCallback:()=>nr,promiseMap:()=>oe,promiseTimeout:()=>pe,removePropertyFromObject:()=>qi,replaceArgsWithNoDashes:()=>el,sanitizeNumberValue:()=>Ir,shouldBlockVirtualIosBuild:()=>rs,spreadObjectToArgs:()=>tl,unescapeHTML:()=>dn,unzipFile:()=>Ze,verifyChecksum:()=>qc});function Ir(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function uv(s){return s=s.toLowerCase(),al.find(e=>e.browserValue===s)}function pn(s,e,t){s=s==null?void 0:s.toLowerCase();let r=al.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||al[0],n=ns.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=ns.find(i=>i.sl.platform===e.platform):e.platformName&&(n=ns.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=ns.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=ns.find(i=>i.bs.platform===t.platform))),is.merge(r,n)}function Rr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH||process.env.GITHUB_BRANCH_NAME}function qi(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&qi(s[r],e,t))}function Fe(s){return s.ELEMENT||s[er]}function zi(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function cl(s=[]){return is.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].sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=is.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function dn(s){return Hm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function mn(s){return[...Hm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function xr(s,e){let t=await Promise.resolve().then(()=>(qe(),Ye));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")}}function qm(s,{visiblePrefixLength:e=1,visibleSuffixLength:t=0,maskCharacter:r="*"}={}){if(!(s!=null&&s.length))return"";let n=.8;if(s.length-(e+t)<s.length*n)return"".padEnd(s.length,r);let o=s.slice(0,e),a=s.slice(s.length-t);return`${o}${r.repeat(Math.ceil(s.length*.9))}${a}`}function kc(s,e){let t=new Set(e),r=n=>{if(!(n===null||typeof n!="object")){if(Array.isArray(n)){n.forEach(i=>r(i));return}for(let i of Object.keys(n))if(t.has(i)){let o=n[i];o!=null&&(n[i]=qm(String(o)))}else typeof n[i]=="object"&&r(n[i])}};return r(s),s}var Wm,is,Vm,Gm,lv,St,$m,ns,al,Ki,Hm,F=I(()=>{"use strict";Wm=R(require("os")),is=R(require("lodash")),Vm=R(require("path")),Gm=require("linkedom");Kr();zc();Lm();Nm();Sc();Lc();Fm();Um();ol();lv=Wm.homedir(),St=Vm.join(lv,".testim-browser-profile"),$m="133",ns=[{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 Tahoe",bs:{os:"OS X",os_version:"Tahoe",safari_version:"26.2"},sl:{},lt:{platform:"MacOS Tahoe"}},{osName:"MacOS Sequoia",bs:{os:"OS X",os_version:"Sequoia",safari_version:"18.4"},sl:{platform:"macOS 15",safari_version:"latest"},lt:{platform:"MacOS Sequoia"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17.3"},sl:{platform:"macOS 14",safari_version:"latest"},lt:{platform:"macOS Sonoma"}},{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"}},{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"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"},lt:{platform:"macOS Big Sur"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{},lt:{platform:"macOS Catalina"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{},lt:{platform:"macOS Mojave"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{},lt:{platform:"macOS High Sierra"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{},lt:{platform:"macOS Sierra"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{},lt:{platform:"OS X El Capitan"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{},lt:{platform:"OS X Yosemite"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{},lt:{platform:"OS X Mountain Lion"}},{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"}}],al=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:$m},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:$m},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"}];Ki=(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]};Hm=new Gm.DOMParser});var ll={};z(ll,{$schema:()=>pv,default:()=>hv,definitions:()=>dv,properties:()=>gv,required:()=>fv,type:()=>mv});var pv,dv,mv,fv,gv,hv,zm=I(()=>{pv="http://json-schema.org/draft-07/schema#",dv={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}}}},mv="object",fv=["entries"],gv={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},hv={$schema:pv,definitions:dv,type:mv,required:fv,properties:gv}});async function ef(){try{return await pe(Ji.promises.readFile(Zi()).then(async s=>{let e=await Zm;return Tv(e,s)}),3e4)}catch{return{}}}function Tv(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=as.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 pt(s,e,t=yv,r=void 0){return async()=>{if(!Xm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await cs(e);if(i)return fn.debug("cache hit:",{fnName:e}),i;if(fn.debug("cache miss:",{fnName:e}),!Ym)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 wv(e,o,t),o}}async function cs(s){let t=(await eo)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function wv(s,e,t){if(ul)throw fn.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 eo;r[s]={value:e,expiry:Date.now()+t},Qm=new Promise(n=>{Qi=n}),bv(r)}catch{fn.error("failed updating cache")}}async function ls(){let s=await eo;Object.keys(s).forEach(e=>{delete s[e]})}function tf(s){Xm=s}function vv(s=!0){Ym=s}async function rf(){try{return ul=!0,await Qm}finally{ul=!1}}function sf(s){Yi=s,eo=ef()}var Ji,Xi,as,Km,fn,Yi,Jm,Qi,Xm,Ym,ul,Qm,Zm,yv,Zi,eo,bv,nf,of,rC,af,Jt=I(()=>{"use strict";Ji=R(require("fs")),Xi=R(require("path")),as=R(require("crypto"));F();Km=require("lodash");W();fn=A("local cache"),Yi=Xi.resolve(wt(),"testim-cache"),Xm=!0,Ym=!0,ul=!1,Qm=new Promise(s=>{Qi=s}),Zm=new Promise(s=>{Jm=s}),yv=1e3*60*60*3,Zi=()=>Xi.resolve(Xi.resolve(Yi,"testim.cache"));eo=ef(),bv=(0,Km.debounce)(async s=>{let e;try{let t=await Zm,r=as.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=as.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await Te(Yi)||await Ji.promises.mkdir(Yi,{recursive:!0}),await Ji.promises.writeFile(Zi(),a)}catch(t){fn.error("failed saving cache",{err:t}),e=t}Qi(e?{success:!1,error:e}:{success:!0})},200);nf=Jm,of=tf.bind(void 0,!1),rC=tf.bind(void 0,!0),af=()=>vv(!1)});function to(){return{cliLocation:wt(),userInfo:us.userInfo(),platform:us.platform(),release:us.release()}}var us,pl=I(()=>{"use strict";us=R(require("node:os"));F()});function Sv(s){try{return ro.resolve(ro.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 ar(s){let e=Sv(s);return require(e)}var ro,gn=I(()=>{"use strict";ro=R(require("path"))});function Ev(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Iv(s){return/The "to" argument must be of type string./.exec(s)}function pf(s,e,t){let r=Ev(s),n=Iv(s);return r||n?(uf.info("Failed to install package due to insufficient write access",{...to(),package:t,path:r}),console.error(`
2
+ "use strict";var Iw=Object.create;var vi=Object.defineProperty;var Rw=Object.getOwnPropertyDescriptor;var xw=Object.getOwnPropertyNames;var Cw=Object.getPrototypeOf,Aw=Object.prototype.hasOwnProperty;var I=(s,e)=>()=>(s&&(e=s(s=0)),e);var z=(s,e)=>{for(var t in e)vi(s,t,{get:e[t],enumerable:!0})},Bd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xw(e))!Aw.call(s,n)&&n!==t&&vi(s,n,{get:()=>e[n],enumerable:!(r=Rw(e,n))||r.enumerable});return s};var R=(s,e,t)=>(t=s!=null?Iw(Cw(s)):{},Bd(e||!s||!s.__esModule?vi(t,"default",{value:s,enumerable:!0}):t,s)),Ke=s=>Bd(vi({},"__esModule",{value:!0}),s);var je={};z(je,{log:()=>M,measure:()=>kw});function M(...s){if(!$d)return;let e=Date.now();console.log(`${e-Pw} ${e-jd} `,...s),jd=e}function kw(s,e){if(!$d)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var $d,Pw,jd,$e=I(()=>{"use strict";$d=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,Pw=Date.now(),jd=Date.now()});var er,qr=I(()=>{"use strict";er="element-6066-11e4-a52e-4f735466cecf"});function ne(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 Je(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 vc(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function Me(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 Sc=I(()=>{"use strict"});var Ic,Wd,Vd,Pi=I(()=>{Ic={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:"2.0.1"},Wd={"@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.4",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.8.1",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6","form-data":"^4.0.4",express:"4.22.1",fkill:"7.2.1","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jsonwebtoken:"9.0.3",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2","node-fetch":"2.7.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":"5.4.12",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",uuid:"11.0.5","validate-npm-package-name":"3.0.0",webdriverio:"9.18.4",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},Vd={node:">= 18.0.0"}});var Tr,wr,Gd,Js,Lw,tr,Hd,qd,ki,it,zd,be,Kd,Jd,Oi,We,Rc,Xd,_i,Yd,Qd,Ex,Ix,Zd,em,tm,rm,xc,sm,Cc,nm,Xs,Ys,ue=I(()=>{"use strict";Tr=process.env.SERVICES_HOST||"https://services.testim.io",wr="https://app.testim.io";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:Tr,Tr=process.env.SERVICES_HOST);Gd=process.env.TESTIM_REGION||"us-west-2",Js=process.env.RUNNER_ENVIRONMENT||"production",Lw={production:"",staging:".staging",development:".dev"},tr=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${Lw[Js]||""}.testim.io`,Hd=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),qd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),ki=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),it=process.env.EDITOR_URL,zd=process.env.WEBSOCKET_HOST||`${Tr}/ws`,be=()=>Tr,Kd=parseInt(process.env.LOGGER_CONSOLE||"0",10),Jd=parseInt(process.env.LOGGER_DEBUG||"0",10),Oi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),We=parseInt(process.env.IS_ON_PREM||"0",10),Rc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Xd=parseInt(process.env.DEBUG_MODE||"0",10),_i=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Yd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",Qd=process.env.CORALOGIX_PRIVATE_KEY||"d0eb01da-f966-1663-63c6-8871225d7c39",Ex=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),Ix=process.env.APPIUM_VERSION||"1.10.1",Zd=process.env.GATEWAY_URL,em=()=>process.env.EXTENSION_SERVICES_HOST||Tr,tm=5*60*1e3,rm=40,xc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",sm=process.env.TDC_DEVICES_API_PATH||"v0",Cc=process.env.TDC_APPS_API_PATH||"v1",nm=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Xs=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Ys=s=>{Tr=s,process.env.SERVICES_HOST=s,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:Tr}});var im,Li,om=I(()=>{"use strict";im=R(require("superagent"));ue();Li=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=Qd,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=im.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 cm={};z(cm,{CoralogixTransport:()=>Ac});var am,Dw,Nw,Ac,lm=I(()=>{"use strict";am=R(require("winston-transport"));om();Dw={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},Nw=["err","error","reason","e"],Ac=class extends am.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new Li({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...c}=t,l={...a,...c},d={severity:Dw[i],text:o,category:n||this.category};l.className&&(d.className=l.className),l.methodName&&(d.methodName=l.methodName),l.threadId&&(d.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let m=!1;a instanceof Error&&(m=!0,l.msg=a.message+a.stack,o&&(l.msg=`${o}
3
+ ${l.msg}`));for(let u of Nw)a[u]instanceof Error&&(l[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(l).length>0&&(o&&!m&&(l.msg=o),d.text=JSON.stringify(l)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function Uw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!We){let{CoralogixTransport:r}=(lm(),Ke(cm)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(Kd){let r={depth:5,colors:!0};s.push(new yt.transports.Console({format:yt.format.combine(yt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),yt.format.timestamp({format:"HH:mm:ss:SSS"}),yt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ni.inspect(n.meta,r)}`))}))}return[s,e,t]}function hm(s){Pc=s}function ym(s){gm=s}function bm(s){We||!s||$w(s)}function pm(s){return{projectId:gm,time:new Date().toISOString(),region:Ht.getRegion(),...Pc&&!s&&{executionId:Pc}}}function A(s){return new Ht(Gw.child({category:s}))}var dm,yt,Ni,Di,mm,Mw,Fw,um,fm,Bw,jw,$w,Ww,Vw,Gw,Pc,gm,Ht,W=I(()=>{"use strict";dm=R(require("node:os")),yt=R(require("winston"));ue();Ni=R(require("node:util"));F();Di=R(require("chalk")),mm=R(require("dayjs"));F();Mw=dm.hostname(),Fw=ot();um={depth:5,colors:!0},fm=(s,e,t)=>{let r=`[${(0,mm.default)().format("HH:mm:ss:SSS")}]`,n=Ni.inspect(e,um),i=Ni.inspect(t,um);return`${Di.default.white(r)} ${Di.default.reset()}SessionPlayer-${Di.default.red(s)} ${n} ${i}`},[Bw,jw,$w]=Uw(),Ww=Jd?"debug":"info",Vw={release:Boolean(!1),branch:"test"},Gw=yt.createLogger({levels:yt.config.syslog.levels,level:Ww,transports:Bw,defaultMeta:{name:"runner",hostname:Mw,nodeVersion:process.version,runnerVersion:Fw,...Vw}}),Pc=null,gm=null;Ht=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)}static setRegion(e){Ht.region=e}static getRegion(){return Ht.region}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;r.user&&(r.user=kc(r.user,["email"]));try{this._logger.log(e,{meta:r,message:t,...pm(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...pm(n)})}catch{}}}waitForFlush(){return jw()}}});var Bi,zr,x,rr,vr,Lt,Mi,Kr,pe,Qs,at,sr,Dt,Fi,Jr,Ui,Zs,Q=I(()=>{"use strict";Bi=require("p-retry"),zr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},x=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},rr=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},vr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},Lt=class extends Bi.AbortError{},Mi=class extends Bi.AbortError{},Kr=class extends Bi.AbortError{},pe=class extends Error{},Qs=class extends Error{},at=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},sr=class extends at{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Dt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Fi=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}},Ui=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Zs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Oc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ie(s){return(0,vm.setTimeout)(s)}function _c(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function le(s,e,t="Timeout Error"){ki&&!Tm&&(Tm=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new pe(t);return e=ki?Number(ki)||6e5:e,Promise.race([s,ie(e).then(()=>{throw r})])}async function oe(s,e,{concurrency:t}={}){if(t){wm||=(await import("p-limit")).default;let r=wm(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function nr(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var vm,Tm,wm,Lc=I(()=>{"use strict";vm=require("timers/promises");Q();ue();Tm=!1});var tn,Sm,qw,en,Em,zw,Kw,Im,Rm=I(()=>{"use strict";tn=R(require("lodash"));ue();Sm=require("dns");W();Lc();qw=A("http-request-counters"),en=!1,Em=async()=>{if(We)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await oe(s,t=>Sm.promises.lookup(t)));return e||(en=!0),e}catch{return qw.error("network connectivity test failed"),en=!0,!1}},zw=tn.throttle(Em,10*1e3),Kw=60*1e3*15,Im=()=>{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)},Kw)}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),en||zw(),a}}}async function r(){if(en||!await Em())return!1;let n=tn.sum([...s.fail.values()]),i=tn.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>en,t}});var Xe={};z(Xe,{deleteReq:()=>rn,didNetworkConnectivityTestFail:()=>jc,download:()=>Uc,get:()=>ve,getFullRes:()=>ev,getText:()=>Mc,head:()=>tv,isNetworkHealthy:()=>Bc,post:()=>Ve,postForm:()=>sn,postText:()=>Zw,put:()=>Fc});function Xw(){return global.caFileContent}function Yw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function Qw(){return!("proxy"in bt.default.Request.prototype)&&global.SuperagentProxy&&global.SuperagentProxy(bt.default),global.proxyUri}function Sr(s,e=!1){let t=Xw();t&&s.ca(t);let r=!e&&Qw();r&&s.proxy(r)}async function xm(s,e,t={},r=Xr,n=0){let i=bt.default.post(s).send(e).timeout(r).set(t);Sr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Nc(s,e,t={},r=Xr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=bt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),Sr(o,i),await o}var bt,Dc,ct,Xr,Jw,qt,rn,Ve,sn,Mc,Zw,ve,ev,tv,Fc,Uc,Bc,jc,Ge=I(()=>{"use strict";bt=R(require("superagent"));W();Rm();Dc=A("http-request"),ct=Im(),Xr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,Jw=6e4;qt=(s,e,t)=>{let r=e.response;e.response instanceof bt.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 Dc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};rn=ct(async(s,e={},t={},r=Xr)=>{try{let n=bt.default.delete(s).send(e).timeout(r).set(t);Sr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return qt("failed to delete request",n,{url:s})}}),Ve=ct(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await xm(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return qt("failed to post request",i,{url:s})}});sn=ct(async(s,e,t,r={},n=Xr)=>{let i=bt.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)}),Sr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return qt("failed to post request",o,{url:s})}});Mc=ct(async(s,e,t)=>{try{return(await Nc(s,e,t)).text}catch(r){return qt("failed to getText request",r,{url:s,query:e})}}),Zw=ct(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await xm(s,e,t,r,n)).text}catch(i){return qt("failed to post request",i,{url:s})}}),ve=ct(async(s,e,t,r,n)=>{try{return(await Nc(s,e,t,r,n)).body}catch(i){return qt("failed to get request",i,{url:s,query:e})}}),ev=ct((s,e,t,r)=>Nc(s,e,t,r)),tv=ct(async s=>{let e=bt.default.head(s).timeout(Xr);Sr(e);try{return await e}catch(t){return qt("failed to head request",t,{url:s})}}),Fc=ct(async(s,e,t={},r=Xr)=>{let n=bt.default.put(s).send(e).timeout(r).set(t);Sr(n);try{return(await n).body}catch(i){return qt("failed to put request",i,{url:s})}}),Uc=ct(async s=>{Dc.info("start to download",{url:s});let e=bt.default.get(s).set("User-Agent","Testim.io").timeout(Jw).buffer(!0).parse(Yw);Sr(e);try{let t=await e;return Dc.info("finished to download",{url:s}),t}catch(t){return qt("failed to download",t,{url:s})}}),Bc=ct.isNetworkHealthy,jc=ct.didNetworkConnectivityTestFail});function Tt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=zt.resolve(__dirname,"../../"):s=zt.resolve(__dirname,""),s):process.cwd()}function ji(s,e){return Me(s)?e||zt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||zt.basename(s)}function ot(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Hc(){try{return Vd.node}catch{return""}}async function Om(s,e,t=!0){let r=await lt.promises.readdir(s,{withFileTypes:!0});await lt.promises.mkdir(e,{recursive:t});for(let n of r){let i=zt.join(s,n.name),o=zt.join(e,n.name);n.isDirectory()?await Om(i,o):await lt.promises.copyFile(i,o)}}async function Te(s){try{return await lt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var zt,Cm,Am,Pm,$c,km,lt,rv,Kt,Ye,$i,Wc,Qe,Vc,Gc,qc,zc=I(()=>{"use strict";zt=R(require("node:path")),Cm=R(require("node:child_process"));Sc();Pi();Am=R(require("unzip-stream")),Pm=R(require("p-retry")),$c=R(require("node:fs")),km=R(require("node:crypto")),lt=require("node:fs"),rv=3;Kt=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Xe));return(0,Pm.default)(()=>e.download(s),{retries:rv,factor:1})},Ye=async(s,e)=>{let t=await Kt(s);return lt.promises.writeFile(e,t.body)};$i=async(s,e)=>{let t=ji(s,e);return Me(s)?Ye(s,t):lt.promises.copyFile(s,t)},Wc=async s=>Me(s)?Kt(s):lt.promises.readFile(s),Qe=async(s,e)=>(0,lt.createReadStream)(s).pipe(Am.Extract({path:e})),Vc=(s,e)=>new Promise((t,r)=>{var o;let n=Cm.spawn("tar",["-xzf",s,"-C",e],{stdio:["ignore","pipe","pipe"]}),i="";(o=n.stderr)==null||o.on("data",a=>{i+=a.toString()}),n.on("error",a=>{r(new Error(`Failed to extract tgz file ${s}: ${a.message}. ${i}`))}),n.on("close",a=>{a!==0&&r(new Error(`Failed to extract tgz file ${s}: tar exited with code ${a}. ${i}`)),t()})}),Gc=s=>(0,lt.statSync)(s).size/1e6;qc=async(s,e,t="sha256",r="hex")=>{let n=await $c.promises.readFile(s),i=km.createHash(t).update(n).digest(r);if(i!==e)throw await $c.promises.unlink(s),new Error(`Checksum mismatch for ${s}. Expected ${e}, got ${i}`)}});var Jt={};z(Jt,{APPIUM_SESSION_MESSAGE:()=>Qc,CLI_MODE:()=>J,MOBILE_APP_SOURCE:()=>Wi,MOBILE_RUN_SKIP_REASON:()=>Yc,OPERANDS:()=>on,REGION_CONFIG:()=>Qr,SEGMENT_CONFIG:()=>Zr,X_HEADER_RUNNER_ID:()=>Zc,gridMessages:()=>wt,gridTypes:()=>N,mobileWeb:()=>Jc,runnerStatus:()=>Kc,runnerTestStatus:()=>he,socketEventTypes:()=>Nt,stepResult:()=>Yr,test:()=>Xc,testRunStatus:()=>nn,testStatus:()=>Ze,timeoutMessages:()=>Pe});var Pe,nn,Kc,he,Ze,wt,Jc,Xc,Nt,J,N,Yr,Wi,Yc,Qc,Zc,Qr,Zr,on,ae=I(()=>{"use strict";Pe={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout",TEST_REACHED_CUSTOM_TIMEOUT_MSG:"test-reached-custom-timeout"},nn={COMPLETED:"completed"},Kc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},he={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Ze={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},wt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Jc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Xc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Nt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},J={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},N={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC"},Yr={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",KEEP_ALIVE_FAILED:"keep-alive-failed"},Wi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Yc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Qc={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"},Zc="X-Testim-Runner-ID",Qr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"},Zr={TTL:1e3*60*60*72,CACHE_FN_NAME:"setSegmentConfig"},on=(t=>(t.AND="AND",t.OR="OR",t))(on||{})});function an(s,e){var t,r,n,i,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(n=s.browser)==null?void 0:n.toLowerCase()]:(i=s.testConfigNames)!=null&&i.length||(o=s.testConfigIds)!=null&&o.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(c=>{var l;return(l=c.runConfig)==null?void 0:l.browserValue}))]:[(a=s.browser)==null?void 0:a.toLowerCase()]}function sv(){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 cn,_m,et,nv,iv,ov,av,cv,el,tl,Lm=I(()=>{"use strict";ae();cn=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},_m=s=>Boolean(s.resultId&&s.source==="remote-run"),et=(s,e)=>s.testStatus===Ze.QUARANTINE&&!_m(e)&&!e.runQuarantinedTests;nv=s=>Boolean(s.loginMode),iv=s=>Boolean(s.tunnelOnlyMode),ov=s=>Boolean(s.createPrefechedData),av=s=>Boolean(s.installLazyDepsMode),cv=s=>Boolean(s.agentMode),el=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},tl=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Gi(s=0){return Vi.default.duration(s).format("HH:mm:ss.SSS")}function rl(s=0){return Vi.default.duration(s).asSeconds()}var Vi,Dm,Hi,Nm=I(()=>{"use strict";Vi=R(require("dayjs")),Dm=R(require("dayjs/plugin/duration"));Vi.default.extend(Dm.default);Hi=s=>{let e=Math.floor(s.asMinutes()),t=s.asSeconds()%60||0;return e>0?`${e} min ${Math.floor(t)} sec`:`${Math.floor(t)} sec`}});var ln,es,ir,Mm,ts,Fm=I(()=>{"use strict";ae();ln=s=>!(!s||"fileName"in s),es=(s,e)=>{if(e===N.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},ir=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Mm=s=>s===N.TESTIM_TVC,ts=(s,e)=>Mm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function sl(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 Um=I(()=>{"use strict"});function jm(s){let e=(0,Bm.default)(s);return e.validForNewPackages||e.validForOldPackages}function nl(s){let e=s.filter(t=>!jm(t.packageName)).map(t=>t.packageName);return e.length>0?e:null}function il(s){let e=s.filter(t=>t&&(t.includes("../")||t.includes("..\\"))).map(t=>t);return e.length>0?e:null}var Bm,ol=I(()=>{"use strict";Bm=R(require("validate-npm-package-name"))});var X={};z(X,{OSS:()=>rs,TESTIM_BROWSER_DIR:()=>vt,buildBasicHeader:()=>vc,calcPercentile:()=>Ki,copyDir:()=>Om,delay:()=>ie,doesPathExist:()=>Te,download:()=>Kt,downloadAndSave:()=>Ye,extractElementId:()=>Be,extractTgz:()=>Vc,formatTimeoutDuration:()=>Hi,getArgsOnRemoteRunFailure:()=>sv,getBrowserInfo:()=>uv,getCdpAddressForHost:()=>Rr,getCliLocation:()=>Tt,getDuration:()=>Gi,getDurationSec:()=>rl,getEnginesVersion:()=>Hc,getEnvironmentGitBranch:()=>Ir,getInvalidPackageNames:()=>nl,getInvalidPackagePaths:()=>il,getLinksFromUnescapeHTML:()=>dn,getLocalFileSizeInMB:()=>Gc,getMemorySnapshot:()=>sl,getPlanType:()=>zi,getRunConfigByBrowserName:()=>un,getRunnerVersion:()=>ot,getSource:()=>$i,getSourceAsBuffer:()=>Wc,getSourcePath:()=>ji,getTestUrl:()=>Je,getUniqBrowsers:()=>an,groupTestsByRetries:()=>cl,guid:()=>ne,hasTestPlanFlag:()=>cn,isAgentMode:()=>cv,isAppFromDevice:()=>ln,isAppFromDeviceDisabled:()=>ts,isCreatePrefetchedDataMode:()=>ov,isInstallLazyDepsMode:()=>av,isLoginMode:()=>nv,isMobileProject:()=>ir,isPromise:()=>Oc,isQuarantineAndNotRemoteRun:()=>et,isRemoteRun:()=>_m,isTestimVirtualGrid:()=>Mm,isTunnelOnlyMode:()=>iv,isURL:()=>Me,isValidPackageName:()=>jm,maskObjectFields:()=>kc,maskSecret:()=>qm,promiseAbort:()=>_c,promiseFromCallback:()=>nr,promiseMap:()=>oe,promiseTimeout:()=>le,removePropertyFromObject:()=>qi,replaceArgsWithNoDashes:()=>el,sanitizeNumberValue:()=>Er,shouldBlockVirtualIosBuild:()=>es,spreadObjectToArgs:()=>tl,unescapeHTML:()=>pn,unzipFile:()=>Qe,verifyChecksum:()=>qc});function Er(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function uv(s){return s=s.toLowerCase(),al.find(e=>e.browserValue===s)}function un(s,e,t){s=s==null?void 0:s.toLowerCase();let r=al.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||al[0],n=rs.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=rs.find(i=>i.sl.platform===e.platform):e.platformName&&(n=rs.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=rs.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=rs.find(i=>i.bs.platform===t.platform))),ss.merge(r,n)}function Ir(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH||process.env.GITHUB_BRANCH_NAME}function qi(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&qi(s[r],e,t))}function Be(s){return s.ELEMENT||s[er]}function zi(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function cl(s=[]){return ss.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].sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=ss.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function pn(s){return Hm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function dn(s){return[...Hm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function Rr(s,e){let t=await Promise.resolve().then(()=>(Ge(),Xe));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")}}function qm(s,{visiblePrefixLength:e=1,visibleSuffixLength:t=0,maskCharacter:r="*"}={}){if(!(s!=null&&s.length))return"";let n=.8;if(s.length-(e+t)<s.length*n)return"".padEnd(s.length,r);let o=s.slice(0,e),a=s.slice(s.length-t);return`${o}${r.repeat(Math.ceil(s.length*.9))}${a}`}function kc(s,e){let t=new Set(e),r=n=>{if(!(n===null||typeof n!="object")){if(Array.isArray(n)){n.forEach(i=>r(i));return}for(let i of Object.keys(n))if(t.has(i)){let o=n[i];o!=null&&(n[i]=qm(String(o)))}else typeof n[i]=="object"&&r(n[i])}};return r(s),s}var Wm,ss,Vm,Gm,lv,vt,$m,rs,al,Ki,Hm,F=I(()=>{"use strict";Wm=R(require("os")),ss=R(require("lodash")),Vm=R(require("path")),Gm=require("linkedom");qr();zc();Lm();Nm();Sc();Lc();Fm();Um();ol();lv=Wm.homedir(),vt=Vm.join(lv,".testim-browser-profile"),$m="133",rs=[{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 Tahoe",bs:{os:"OS X",os_version:"Tahoe",safari_version:"26.2"},sl:{},lt:{platform:"MacOS Tahoe"}},{osName:"MacOS Sequoia",bs:{os:"OS X",os_version:"Sequoia",safari_version:"18.4"},sl:{platform:"macOS 15",safari_version:"latest"},lt:{platform:"MacOS Sequoia"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17.3"},sl:{platform:"macOS 14",safari_version:"latest"},lt:{platform:"macOS Sonoma"}},{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"}},{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"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"},lt:{platform:"macOS Big Sur"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{},lt:{platform:"macOS Catalina"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{},lt:{platform:"macOS Mojave"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{},lt:{platform:"macOS High Sierra"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{},lt:{platform:"macOS Sierra"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{},lt:{platform:"OS X El Capitan"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{},lt:{platform:"OS X Yosemite"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{},lt:{platform:"OS X Mountain Lion"}},{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"}}],al=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:$m},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:$m},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"}];Ki=(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]};Hm=new Gm.DOMParser});var ll={};z(ll,{$schema:()=>pv,default:()=>hv,definitions:()=>dv,properties:()=>gv,required:()=>fv,type:()=>mv});var pv,dv,mv,fv,gv,hv,zm=I(()=>{pv="http://json-schema.org/draft-07/schema#",dv={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}}}},mv="object",fv=["entries"],gv={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},hv={$schema:pv,definitions:dv,type:mv,required:fv,properties:gv}});async function ef(){try{return await le(Ji.promises.readFile(Zi()).then(async s=>{let e=await Zm;return Tv(e,s)}),3e4)}catch{return{}}}function Tv(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=is.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 ut(s,e,t=yv,r=void 0){return async()=>{if(!Xm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await os(e);if(i)return mn.debug("cache hit:",{fnName:e}),i;if(mn.debug("cache miss:",{fnName:e}),!Ym)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 wv(e,o,t),o}}async function os(s){let t=(await eo)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function wv(s,e,t){if(ul)throw mn.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 eo;r[s]={value:e,expiry:Date.now()+t},Qm=new Promise(n=>{Qi=n}),bv(r)}catch{mn.error("failed updating cache")}}async function as(){let s=await eo;Object.keys(s).forEach(e=>{delete s[e]})}function tf(s){Xm=s}function vv(s=!0){Ym=s}async function rf(){try{return ul=!0,await Qm}finally{ul=!1}}function sf(s){Yi=s,eo=ef()}var Ji,Xi,is,Km,mn,Yi,Jm,Qi,Xm,Ym,ul,Qm,Zm,yv,Zi,eo,bv,nf,of,rC,af,Xt=I(()=>{"use strict";Ji=R(require("fs")),Xi=R(require("path")),is=R(require("crypto"));F();Km=require("lodash");W();mn=A("local cache"),Yi=Xi.resolve(Tt(),"testim-cache"),Xm=!0,Ym=!0,ul=!1,Qm=new Promise(s=>{Qi=s}),Zm=new Promise(s=>{Jm=s}),yv=1e3*60*60*3,Zi=()=>Xi.resolve(Xi.resolve(Yi,"testim.cache"));eo=ef(),bv=(0,Km.debounce)(async s=>{let e;try{let t=await Zm,r=is.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=is.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await Te(Yi)||await Ji.promises.mkdir(Yi,{recursive:!0}),await Ji.promises.writeFile(Zi(),a)}catch(t){mn.error("failed saving cache",{err:t}),e=t}Qi(e?{success:!1,error:e}:{success:!0})},200);nf=Jm,of=tf.bind(void 0,!1),rC=tf.bind(void 0,!0),af=()=>vv(!1)});function to(){return{cliLocation:Tt(),userInfo:cs.userInfo(),platform:cs.platform(),release:cs.release()}}var cs,pl=I(()=>{"use strict";cs=R(require("node:os"));F()});function Sv(s){try{return ro.resolve(ro.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 ar(s){let e=Sv(s);return require(e)}var ro,fn=I(()=>{"use strict";ro=R(require("path"))});function Ev(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Iv(s){return/The "to" argument must be of type string./.exec(s)}function pf(s,e,t){let r=Ev(s),n=Iv(s);return r||n?(uf.info("Failed to install package due to insufficient write access",{...to(),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.
7
7
  Testim had missing write access to ${r||e}
8
8
 
9
- `),!0):!1}function dl(s){try{return ar(s)}catch{return!1}}function df(s,e){let t=hn.join(s,`./node_modules/${e}/package.json`);return JSON.parse(ps.readFileSync(t,"utf-8")).version}function mf(s){if(typeof s=="string"&&s.endsWith(".cjs"))return s;if(typeof s=="object"&&s!==null)for(let e of Object.keys(s).filter(t=>t!=="browser")){let t=mf(s[e]);if(t)return t}}function ff(s){let e=hn.join(s,"package.json"),t=JSON.parse(ps.readFileSync(e,"utf-8"));if(!("exports"in t))return"";let r=mf(t);if(!r)throw new Ui(t.name);return r}async function no(s,e,t){let r=hn.join(s,"npm-shrinkwrap.json"),n=hn.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await Te(r)&&(await ps.promises.rename(r,n),i=!0)}catch{}return await lf(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw pf(o.stderr,s,e)?new Yr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await ps.promises.rename(n,r)}catch{}}}function ml(s,e,t,r,n=!0){return new Promise((i,o)=>{var h,g,y,w;let a=t?["--proxy",t]:[],c=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},l="",d="",m=["--no-save","--no-package-lock","--no-prune","--no-audit","--progress=false"];n&&m.push("--prefer-offline");let u="npm";process.platform==="win32"&&(u="npm.cmd",c.shell=!0);let f=(0,so.spawn)(u,["i","--prefix",s,...m,...e,...a],c);(h=f.stderr)==null||h.pipe(process.stderr),(g=f.stdout)==null||g.pipe(process.stdout),(y=f.stdout)==null||y.on("data",S=>{l+=S}),(w=f.stderr)==null||w.on("data",S=>{d+=S}),f.on("close",S=>{var b,v;if(S){n&&ml(s,e,t,r,!1).then(i).catch(o);let T;try{let C=(b=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(d))==null?void 0:b[1],_=(v=/No matching version found for (\S+)@/gm.exec(d))==null?void 0:v[1];C||_?T=`404 Not Found - GET https://registry.npmjs.org/${_??C} - Not found`:pf(d,s)?T=`insufficient write access in location ${s}`:T=`Npm Installation closed with exit code ${S} with error: ${d}`}catch(C){T=`Npm Install closed with exit code ${S}
9
+ `),!0):!1}function dl(s){try{return ar(s)}catch{return!1}}function df(s,e){let t=gn.join(s,`./node_modules/${e}/package.json`);return JSON.parse(ls.readFileSync(t,"utf-8")).version}function mf(s){if(typeof s=="string"&&s.endsWith(".cjs"))return s;if(typeof s=="object"&&s!==null)for(let e of Object.keys(s).filter(t=>t!=="browser")){let t=mf(s[e]);if(t)return t}}function ff(s){let e=gn.join(s,"package.json"),t=JSON.parse(ls.readFileSync(e,"utf-8"));if(!("exports"in t))return"";let r=mf(t);if(!r)throw new Ui(t.name);return r}async function no(s,e,t){let r=gn.join(s,"npm-shrinkwrap.json"),n=gn.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await Te(r)&&(await ls.promises.rename(r,n),i=!0)}catch{}return await lf(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw pf(o.stderr,s,e)?new Jr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await ls.promises.rename(n,r)}catch{}}}function ml(s,e,t,r,n=!0){return new Promise((i,o)=>{var h,g,y,w;let a=t?["--proxy",t]:[],c=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},l="",d="",m=["--no-save","--no-package-lock","--no-prune","--no-audit","--progress=false"];n&&m.push("--prefer-offline");let u="npm";process.platform==="win32"&&(u="npm.cmd",c.shell=!0);let f=(0,so.spawn)(u,["i","--prefix",s,...m,...e,...a],c);(h=f.stderr)==null||h.pipe(process.stderr),(g=f.stdout)==null||g.pipe(process.stdout),(y=f.stdout)==null||y.on("data",S=>{l+=S}),(w=f.stderr)==null||w.on("data",S=>{d+=S}),f.on("close",S=>{var b,v;if(S){n&&ml(s,e,t,r,!1).then(i).catch(o);let T;try{let C=(b=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(d))==null?void 0:b[1],_=(v=/No matching version found for (\S+)@/gm.exec(d))==null?void 0:v[1];C||_?T=`404 Not Found - GET https://registry.npmjs.org/${_??C} - Not found`:pf(d,s)?T=`insufficient write access in location ${s}`:T=`Npm Installation closed with exit code ${S} with error: ${d}`}catch(C){T=`Npm Install closed with exit code ${S}
10
10
  err: ${C}
11
- stdout: ${l} stderr: ${d}`}uf.info(`Npm Install closed with exit code ${S}`,{message:T,stderr:d}),o(new Nt(T))}else i(l)}),setTimeout(()=>{try{f.kill()}finally{o(new ue)}},r)})}async function gf(){try{return(await lf("npm -v")).stdout.trim()}catch{return""}}var ps,hn,cf,so,lf,uf,ds=I(()=>{"use strict";ps=R(require("fs")),hn=R(require("path"));F();cf=require("util"),so=require("child_process");W();pl();gn();Q();lf=(0,cf.promisify)(so.exec),uf=A("cli-service")});var U,yf,bf,Tf,Rv,xv,Cv,hf,io,gl,O,me=I(()=>{"use strict";U=R(require("rox-node")),yf=R(require("node-fetch")),bf=require("eventsource");W();F();le();Tf=A("FeatureFlagsService"),Rv=!Ge&&!0&&!Zd,xv=2e4,Cv=60*60*24,hf=["labs","disabled","enabled"],io=class extends U.default.RoxString{constructor(e="disabled"){super(e,hf)}getValue(){let e=super.getValue();return hf.includes(e)?e:(Tf.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},gl=class{constructor(){this.flags={useNewWSCLI:new U.default.Flag,useSafariWebdriverVisibilityChecks:new U.default.Flag,useClickimVisibilityChecks:new U.default.Flag,runGetElementCodeInAut:new U.default.Flag,enableFrameSwitchOptimization:new U.default.Flag,maximumJsResultSize:new U.default.RoxNumber(2e3*1024),skipFileInputClicks:new U.default.Flag,errorMessageOnBadNetwork:new U.default.Flag(!0),warnOnBadNetwork:new U.default.Flag(!1),overrideAzureStorageUrl:new U.default.Flag,autoSaveDownloadFileFireFox:new U.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new U.default.Flag(!0),experimentalPreCodeCompilation:new U.default.Flag(!0),experimentalAsyncCustomCode:new U.default.Flag,useSameBrowserForMultiTests:new io("labs"),highSpeedMode:new io,usePortedHtml5DragDrop:new U.default.Flag,testNamesToBeforeSuiteHook:new U.default.Flag,addCustomCapabilities:new U.default.RoxString("{}"),addCustomLTtunnelNTLMOptions:new U.default.RoxString("{}"),LTNetworkCapabilities:new U.default.Flag,downloadToBase64:new U.default.Flag,publicGridURL:new U.default.RoxString("public-grid.testim.io"),allowAppFromDeviceRuns:new U.default.Flag(!0),unsupportedCapsFields:new U.default.RoxString("[]"),dontFocusOnInit:new U.default.Flag,retryOnSeleniumHubError:new U.default.Flag,enableLambdaTestTunnelNTLM:new U.default.Flag,enableLambdaTestTunnelSkipUpgrade:new U.default.Flag,tdcHsPreventNetworkCapture:new U.default.Flag,enableBatchTDC:new U.default.Flag,clearRunnerFileCache:new U.default.Flag,forceTurboModeIfNeeded:new U.default.Flag,redisSlotManager:new U.default.Flag,tunnelBinaryNewVersion:new U.default.Flag(!1),encryptedCredentials:new U.default.Flag,computePackagePathFromPackageJsonExports:new U.default.Flag,sendExtensionOnEdgeNonLinux:new U.default.Flag,reuseCliPkgInstallFolder:new U.default.Flag,getPublicIpFrom3rdPartyServices:new U.default.Flag,chromedriverCdnBinariesUrl:new U.default.RoxString(""),sfdcHybridCompany:new U.default.Flag,allowFixingAppIdStructure:new U.default.Flag,enableAppium2BrowserStack:new U.default.Flag,increaseTDCRequestTimeout:new U.default.Flag,accessTokenExpiryMargin:new U.default.RoxNumber(300*1e3),useMV3Extension:new U.default.Flag,testimHeadlessExtensionDownloadUrl:new U.default.RoxString("",[]),applyMobileRestrictionFromDate:new U.default.RoxNumber(17235072e5),removeMobileTrialRestrictions:new U.default.Flag,appiumConnectionRetryCount:new U.default.RoxNumber(0),appiumConnectionRequestTimeout:new U.default.RoxNumber(12e4),DFBrowserVersion:new U.default.RoxString("latest",["latest","latest-1","latest-2"]),DFAcceptInsecureOrigins:new U.default.RoxString("http://jsbin.testim.io"),enableFixForCustomExtensionForLT:new U.default.Flag(!1),enableTestPlanAggregation:new U.default.Flag,secrets:new U.default.Flag,chromeArgsDisableFeatures:new U.default.RoxString(""),useNgrokTunnel:new U.default.Flag(!1)},U.default.register("default",this.flags)}setProjectId(e){U.default.setCustomStringProperty("projectId",e)}setProjectType(e){U.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){U.default.setCustomStringProperty("productType",e)}setCompanyId(e){U.default.setCustomStringProperty("companyId",e)}setPlanType(e){U.default.setCustomStringProperty("planType",e)}setIsPOC(e){U.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){U.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){U.default.setCustomStringProperty("runnerMode",e)}setRunnerEnvironment(e){U.default.setCustomStringProperty("runnerEnvironment",e)}async fetch({proxy:e}){let t,r,n;if(!Rv)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,c)=>(0,yf.default)(a,{...c,agent:o}),n=function(a){return new bf.EventSource(a,{fetch:r})}}let i={fetchIntervalInSec:Cv,fetchFunction:r,eventSourceImpl:n};return pe(U.default.setup(Yd,i),xv).catch(o=>Tf.error("failed to get feature flag status",o))}},O=new gl});var Ef={};z(Ef,{install:()=>Pv,isReady:()=>Ov,start:()=>kv});var wf,vf,Sf,yl,hl,Av,Pv,kv,Ov,If=I(()=>{"use strict";wf=R(require("fkill")),vf=R(require("p-retry"));ds();qe();F();gn();me();Sf="chromedriver",yl=9515,hl=`http://localhost:${yl}/wd/hub`,Av=[`--port=${yl}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],Pv=async()=>{let s=O.flags.chromedriverCdnBinariesUrl.getValue(),e=Me(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await no(wt(),`${Sf} --detect_chromedriver_version ${e}`)},kv=async()=>{process.env.NODE_OPTIONS="",await(0,wf.default)(`:${yl}`,{silent:!0}),await ar(Sf).start(Av,!0)},Ov=async({chromeBinaryLocation:s})=>{await(0,vf.default)(async()=>{var n;let e=await ve(`${hl}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await He({url:`${hl}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!r||r.status!==0||!r.sessionId)throw new Error("create session failed");await sn(`${hl}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var bn={};z(bn,{getSessionPlayerFolder:()=>vl,prepareChromeDriver:()=>yn,prepareCustomExtension:()=>Tl,prepareExtension:()=>wl,preparePlayer:()=>Cr});async function Tl(s,e=!1){if(!s)return;if(Me(s)){let n=ms.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await _v(s)>bl&&!e)throw new x(Rf);return await Qe(s,n),n}let t=ms.resolve(s);if(!Cf.existsSync(t))throw new x(`Failed to find custom extension in location: ${t}`);if(Gc(t)>bl&&!e)throw new x(Rf);return t}async function _v(s){let e=(qe(),Je(Ye));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw oo.warn("failed to download custom extension",{err:t}),new x(`Failed to download custom extension from location: ${s}`)}}function wl(s){oo.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:ji(t)}));return pt(()=>oe(e,({location:t,path:r})=>$i(t,r)),"prepareExtension",Pf,e)()}async function yn(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(If(),Ef));try{await i.install(),await i.start(),t||await i.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof Yr||(oo.error(a,{...s,...to(),error:(0,Af.serializeError)(o)}),console.log(`
11
+ stdout: ${l} stderr: ${d}`}uf.info(`Npm Install closed with exit code ${S}`,{message:T,stderr:d}),o(new Dt(T))}else i(l)}),setTimeout(()=>{try{f.kill()}finally{o(new pe)}},r)})}async function gf(){try{return(await lf("npm -v")).stdout.trim()}catch{return""}}var ls,gn,cf,so,lf,uf,us=I(()=>{"use strict";ls=R(require("fs")),gn=R(require("path"));F();cf=require("util"),so=require("child_process");W();pl();fn();Q();lf=(0,cf.promisify)(so.exec),uf=A("cli-service")});var U,yf,bf,Tf,Rv,xv,Cv,hf,io,gl,O,me=I(()=>{"use strict";U=R(require("rox-node")),yf=R(require("node-fetch")),bf=require("eventsource");W();F();ue();Tf=A("FeatureFlagsService"),Rv=!We&&!0&&!Zd,xv=2e4,Cv=60*60*24,hf=["labs","disabled","enabled"],io=class extends U.default.RoxString{constructor(e="disabled"){super(e,hf)}getValue(){let e=super.getValue();return hf.includes(e)?e:(Tf.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},gl=class{constructor(){this.flags={useNewWSCLI:new U.default.Flag,useSafariWebdriverVisibilityChecks:new U.default.Flag,useClickimVisibilityChecks:new U.default.Flag,runGetElementCodeInAut:new U.default.Flag,enableFrameSwitchOptimization:new U.default.Flag,maximumJsResultSize:new U.default.RoxNumber(2e3*1024),skipFileInputClicks:new U.default.Flag,errorMessageOnBadNetwork:new U.default.Flag(!0),warnOnBadNetwork:new U.default.Flag(!1),overrideAzureStorageUrl:new U.default.Flag,autoSaveDownloadFileFireFox:new U.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new U.default.Flag(!0),experimentalPreCodeCompilation:new U.default.Flag(!0),experimentalAsyncCustomCode:new U.default.Flag,useSameBrowserForMultiTests:new io("labs"),highSpeedMode:new io,usePortedHtml5DragDrop:new U.default.Flag,testNamesToBeforeSuiteHook:new U.default.Flag,addCustomCapabilities:new U.default.RoxString("{}"),addCustomLTtunnelNTLMOptions:new U.default.RoxString("{}"),LTNetworkCapabilities:new U.default.Flag,downloadToBase64:new U.default.Flag,publicGridURL:new U.default.RoxString("public-grid.testim.io"),allowAppFromDeviceRuns:new U.default.Flag(!0),unsupportedCapsFields:new U.default.RoxString("[]"),dontFocusOnInit:new U.default.Flag,retryOnSeleniumHubError:new U.default.Flag,enableLambdaTestTunnelNTLM:new U.default.Flag,enableLambdaTestTunnelSkipUpgrade:new U.default.Flag,tdcHsPreventNetworkCapture:new U.default.Flag,enableBatchTDC:new U.default.Flag,clearRunnerFileCache:new U.default.Flag,forceTurboModeIfNeeded:new U.default.Flag,redisSlotManager:new U.default.Flag,tunnelBinaryNewVersion:new U.default.Flag(!1),encryptedCredentials:new U.default.Flag,computePackagePathFromPackageJsonExports:new U.default.Flag,sendExtensionOnEdgeNonLinux:new U.default.Flag,reuseCliPkgInstallFolder:new U.default.Flag,getPublicIpFrom3rdPartyServices:new U.default.Flag,chromedriverCdnBinariesUrl:new U.default.RoxString(""),sfdcHybridCompany:new U.default.Flag,allowFixingAppIdStructure:new U.default.Flag,enableAppium2BrowserStack:new U.default.Flag,increaseTDCRequestTimeout:new U.default.Flag,accessTokenExpiryMargin:new U.default.RoxNumber(300*1e3),useMV3Extension:new U.default.Flag,testimHeadlessExtensionDownloadUrl:new U.default.RoxString("",[]),applyMobileRestrictionFromDate:new U.default.RoxNumber(17235072e5),removeMobileTrialRestrictions:new U.default.Flag,appiumConnectionRetryCount:new U.default.RoxNumber(0),appiumConnectionRequestTimeout:new U.default.RoxNumber(12e4),DFBrowserVersion:new U.default.RoxString("latest",["latest","latest-1","latest-2"]),DFAcceptInsecureOrigins:new U.default.RoxString("http://jsbin.testim.io"),enableFixForCustomExtensionForLT:new U.default.Flag(!1),enableTestPlanAggregation:new U.default.Flag,secrets:new U.default.Flag,chromeArgsDisableFeatures:new U.default.RoxString(""),useNgrokTunnel:new U.default.Flag(!1)},U.default.register("default",this.flags)}setProjectId(e){U.default.setCustomStringProperty("projectId",e)}setProjectType(e){U.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){U.default.setCustomStringProperty("productType",e)}setCompanyId(e){U.default.setCustomStringProperty("companyId",e)}setPlanType(e){U.default.setCustomStringProperty("planType",e)}setIsPOC(e){U.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){U.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){U.default.setCustomStringProperty("runnerMode",e)}setRunnerEnvironment(e){U.default.setCustomStringProperty("runnerEnvironment",e)}async fetch({proxy:e}){let t,r,n;if(!Rv)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,c)=>(0,yf.default)(a,{...c,agent:o}),n=function(a){return new bf.EventSource(a,{fetch:r})}}let i={fetchIntervalInSec:Cv,fetchFunction:r,eventSourceImpl:n};return le(U.default.setup(Yd,i),xv).catch(o=>Tf.error("failed to get feature flag status",o))}},O=new gl});var Ef={};z(Ef,{install:()=>Pv,isReady:()=>Ov,start:()=>kv});var wf,vf,Sf,yl,hl,Av,Pv,kv,Ov,If=I(()=>{"use strict";wf=R(require("fkill")),vf=R(require("p-retry"));us();Ge();F();fn();me();Sf="chromedriver",yl=9515,hl=`http://localhost:${yl}/wd/hub`,Av=[`--port=${yl}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],Pv=async()=>{let s=O.flags.chromedriverCdnBinariesUrl.getValue(),e=Me(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await no(Tt(),`${Sf} --detect_chromedriver_version ${e}`)},kv=async()=>{process.env.NODE_OPTIONS="",await(0,wf.default)(`:${yl}`,{silent:!0}),await ar(Sf).start(Av,!0)},Ov=async({chromeBinaryLocation:s})=>{await(0,vf.default)(async()=>{var n;let e=await ve(`${hl}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Ve({url:`${hl}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!r||r.status!==0||!r.sessionId)throw new Error("create session failed");await rn(`${hl}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var yn={};z(yn,{getSessionPlayerFolder:()=>vl,prepareChromeDriver:()=>hn,prepareCustomExtension:()=>Tl,prepareExtension:()=>wl,preparePlayer:()=>xr});async function Tl(s,e=!1){if(!s)return;if(Me(s)){let n=ps.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await _v(s)>bl&&!e)throw new x(Rf);return await Ye(s,n),n}let t=ps.resolve(s);if(!Cf.existsSync(t))throw new x(`Failed to find custom extension in location: ${t}`);if(Gc(t)>bl&&!e)throw new x(Rf);return t}async function _v(s){let e=(Ge(),Ke(Xe));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw oo.warn("failed to download custom extension",{err:t}),new x(`Failed to download custom extension from location: ${s}`)}}function wl(s){oo.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:ji(t)}));return ut(()=>oe(e,({location:t,path:r})=>$i(t,r)),"prepareExtension",Pf,e)()}async function hn(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(If(),Ef));try{await i.install(),await i.start(),t||await i.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof Jr||(oo.error(a,{...s,...to(),error:(0,Af.serializeError)(o)}),console.log(`
12
12
  1. If you don't have Chrome, please install it from https://www.google.com/chrome.
13
13
  2. If Chrome is installed, please verify it's binary directory:
14
14
  - installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
15
15
  - exists in your PATH environment variables.
16
16
  3. Try adding --chrome-binary-location flag to Testim CLI specifying the exact location of chrome binary in your computer (e.g on Windows "C:/Program Files/Google/Chrome/Application/chrome.exe").
17
- 4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),o}}async function Lv(){let s=`${tr}/sessionPlayer_LATEST_RELEASE`;return(await zt(s)).body.toString("utf8")}async function Dv(s,e){if(!Me(s)||Me(s)&&e||Ge)return s;let t=await Lv();return`${s}-${t}`}function vl(){let s=wt();return ms.resolve(s,"testim-bin")}function Nv(){let s=vl();return ms.resolve(s,"sessionPlayer.zip")}async function kf(s,e,t=!1){try{return await $i(s,e),await Ze(e,vl())}catch(r){if(t)throw r;return await kf(s,e,!0)}}async function Cr(s,e){oo.info("prepare player",{location:s,canary:e});let t=Nv();return pt(async()=>{let r=await Dv(s,e);return await kf(r,t),{}},"preparePlayer",Pf,[s,e,t])()}var xf,Cf,ms,Af,oo,Pf,bl,Rf,Tn=I(()=>{"use strict";xf=R(require("ms")),Cf=R(require("node:fs")),ms=R(require("node:path"));le();Jt();Af=require("serialize-error");W();pl();Q();F();oo=A("prepare runner and testim start"),Pf=(0,xf.default)("0.5 day"),bl=16,Rf=`The size of the custom extension is more than ${bl}MB`});function Mv(){let s=wn.type().toLowerCase();return s==="darwin"?wn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?wn.arch()==="x64"?"win64":"win32":"linux"}async function co(){let s=Mv(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new x(`Unsupported platform: ${s}`);let r=parseInt(vn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},i={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},o=`${e}/${t[s]}/${vn}/${n[s]}.zip`,a=ao.join(Sl,n[s]),c=`${a}.zip`,l=ao.join(a,i[s]);if(await Te(l))return l;if(!await Te(c)){let m=(0,El.default)("Downloading Chromium").start();try{await Of.promises.mkdir(Sl),await Qe(o,c)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,El.default)("Extracting Chromium").start();try{await Ze(c,Sl)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),l}var Of,wn,ao,El,vn,Sl,Il=I(()=>{"use strict";Of=R(require("fs")),wn=R(require("os")),ao=R(require("path")),El=R(require("ora"));Q();F();vn="1000968",Sl=ao.join(St,`chrome-${vn}`)});async function Df(s,e){return Ar=s,Al=e,await Rl()}function Nf(s,e){Ar=e.projectId,Al=e.token,Sn=e.userAccessKey,dt=s.token,In=Pl(dt),Rn=s.refreshToken,xl=s.ngrokToken,Cl=s.isNgrokWhitelisted,_f=e.publicIp,Lf=e.initializedFromCache}function Uv(s=Ar,e=Al){return pt(()=>(En.info("request to get cli token from server"),He({url:`${be()}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Fv*10,{projectId:s,token:e})()}async function Bv(){En.info("request to refresh JWT cli token from server");let s=await He({url:`${be()}/auth/refreshToken`,body:{token:dt,refreshToken:Rn}});return dt=s.token,In=Pl(dt),s.refreshToken&&(Rn=s.refreshToken),dt}async function Rl(){try{let s=await Uv();return En.info("successfully get cli token from server"),dt=s.token,In=Pl(dt),Rn=s.refreshToken,xl=s.ngrokToken,Cl=s.isNgrokWhitelisted,dt}catch(s){throw s.message.includes("Unauthorized")?new x("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(En.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Ar}),new x(`While trying to retrieve CLI token, caught error: ${s}`))}}function Pl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Ft(){if(!In)return Rl();let s=O.flags.accessTokenExpiryMargin.getValue();if(In<Date.now()+4*s)try{return await Bv()}catch(e){return En.error("failed to refresh token, executing fallback",e),Rl()}return dt}function lo(){return Rn}function Pr(){return dt?{uid:require("jsonwebtoken").decode(dt).id,ngrokToken:xl,isNgrokWhitelisted:Cl}:{}}async function uo(){if(!Sn||!Ar)return;if(await kl({userAccessKey:Sn,projectId:Ar}))return Sn;let e=`user access key "${Sn}" is invalid for project "${Ar}"`;throw new x(e)}function po(){return _f}function mo(){return Lf}var En,dt,In,Rn,xl,Cl,Ar,Al,Sn,_f,Lf,Fv,mt=I(()=>{"use strict";le();qe();Jt();Q();W();ye();me();En=A("testim-custom-token"),Ar=null,Al=null,Fv=5*60*1e3});function jv(s){if(s.protocol)return s.protocol;if([N.TESTIM_PRIVATE,N.TESTIM,N.BROWSERSTACK,N.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([N.TESTIM_ENTERPRISE,N.TESTIM_LAMBDATEST,N.DEVICE_FARM].includes(s.type)){let e=Mf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function $v(s){let e=Mf.exec(s);return e==null?void 0:e[3]}function go(s){var v,T,C,_,B,G,E,k,D,j,V;let e=s&&$v(s.host),t=s.port,r=s.path,n=s&&jv(s),i=s.token,o=s.slotId,a=(v=s.hybrid)==null?void 0:v.tunnel,c=(T=s.external)==null?void 0:T.user,l=(C=s.external)==null?void 0:C.key,d=s.type,m=d===N.HYBRID?a&&((G=(B=(_=s.hybrid)==null?void 0:_.external)==null?void 0:B[s.hybrid.tunnel])==null?void 0:G.user):c,u=d===N.HYBRID?a&&((D=(k=(E=s.hybrid)==null?void 0:E.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:D.key):l,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(j=s.mobileTokens)==null?void 0:j.androidToken,w=(V=s.mobileTokens)==null?void 0:V.iosToken,S=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:c,key:l,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:w,apiUrl:S,isSupportGrid:b}}async function Vv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(c){throw ft.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(vt.UNKNOWN)}if(ft.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw ft.error("invalid response - get grid",{res:o}),new Error(vt.UNKNOWN);if(o.status==="success"){if(o.grid.mode==="local")return{mode:"local"};((a=o.grid)==null?void 0:a.mode)==="custom"&&Object.assign(o.grid,jf(n));let c=go(o.grid);return Wv(t,e,c.gridId,c.slotId,r,c.isSupportGrid),c}throw o.code==="not-found"?new ct(vt.NOT_FOUND):o.code==="no-available-slot"?new sr(`Failed to run test on ${r} - concurrency limit reached`):(ft.error("invalid code error response - get grid",{res:o}),new ct(vt.UNKNOWN))}function Uf(s){return Ml(s)}async function Bf(s,e,t){let n=(t||await Uf(s)).find(i=>i._id===e);if(!n)throw new x(`Failed to find grid id: ${e}`);return go(n)}async function Gv(s,e,t){let n=(t||await Uf(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new x(`Failed to find grid name: ${e}`);return go(n)}async function Ol(s,e){let t=xn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete xn[s],!a){if(!r){ft.warn("failed to find grid slot id",{projectId:e});return}ft.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await Ll(o,e,r,n,i)}catch(c){ft.error("failed to release slot",{projectId:e,err:c})}}}async function Hv(s){let e=Object.values(xn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid)try{await _l(s,e)}catch(t){ft.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}function qv(s){Ff=global.setInterval(Hv,1e4,s)}async function zv(s){let e=Object.keys(xn);if(e.length){ft.warn("not all slots released before end runner flow",{projectId:s});try{await oe(e,t=>Ol(Number(t),s))}catch(t){ft.error("failed to release all slots",{err:t,projectId:s})}}}async function Kv(s){await zv(s),clearInterval(Ff)}function Jv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function Xv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function jf(s){let t=(()=>fo.isEmpty(s.testobjectSauce)?fo.isEmpty(s.saucelabs)?fo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=Jv(t,s),c=Xv(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:c,key:a,gridId:ne()}}async function $f(s,e){let t=s.company.companyId;return await Bf(t,e.gridId,s.allGrids)}async function Wf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:c}=s;if(n||o||i)return{mode:"local"};if(r)return jf(s);let l=t==null?void 0:t.companyId;if(a)return Bf(l,a,e);if(c)return Gv(l,c,e);if(ln(s)||s.tunnelOnlyMode){ft.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new ct("Missing host or grid configuration")}async function Vf(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:c,localTmaUrl:l,useLocalChromeDriver:d,useChromeLauncher:m,company:u}=t,f=Boolean(d||m||l),h=u==null?void 0:u.companyId;return Vv(o,h,r,s,t,()=>Nl({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:i,testResultId:n}))}var fo,ft,xn,Mf,Ff,Wv,Cn,Gf,fs=I(()=>{"use strict";fo=R(require("lodash"));ye();W();F();ae();Q();ft=A("grid-service"),xn={},Mf=/(^(https?):\/{2})?(.*)/,Ff=null;Wv=(s,e,t,r,n,i)=>{xn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};Cn={start:qv,end:Kv};Gf=async(s={},e={},t={},r={},n={})=>{var g,y,w;let{company:{companyId:i}={},project:o}=s,{gridId:a,type:c}=e,l=s.browser||t.browserValue,d=Boolean(s.tunnel),{maxRetries:m,currentRetry:u}=n;if(!a||!c||((c===N.TESTIM_LAMBDATEST||c===N.LAMBDATEST)&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e,i,o)),c!==N.HYBRID||!i||!l||!m||!u))return e;let f=await Dl({companyId:i,gridId:a,maxRetries:m,currentRetry:u,browser:l,usingTunnel:d});ft.info("handling hybrid grid",{response:f,companyId:i});let h=go({...e,...f.connectionDetails,provider:f.provider});return f.provider!=="lambdatest"&&((y=r.disable)==null||y.call(r)),f.provider==="lambdatest"&&await((w=r.enableIfNeeded)==null?void 0:w.call(r,h,i,o)),h}});function Pn(){return ho||"master"}function Hf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){ho="master";return}if(s!=null&&s.isArchived)throw new x(`Branch ${s.branch} is archived, run aborted.`);if(s){ho=s.branch||s;return}ho=e?"master":void 0}var ho,Fl=I(()=>{"use strict";Q()});function Kf(s){if(!Ge){if(s!=null&&s.userId||(s={anonymousId:"runnerId"}),!Et){cs(ts.CACHE_FN_NAME).then(e=>{Et=new yo.Analytics({writeKey:e||zf,flushAt:1}),Et.identify(s)});return}Et.identify(s)}}function gt(s,e){return gs("ci",s,e)}function gs(s,e,t){if(Ge)return;let r=s?{userId:s}:{anonymousId:"runnerId"};if(!Et){cs(ts.CACHE_FN_NAME).then(n=>{Et=new yo.Analytics({writeKey:n||zf,flushAt:1}),Et==null||Et.track(Object.assign(r,{event:e,properties:t}))});return}Et.track(Object.assign(r,{event:e,properties:t}))}function Jf(s){s&&(Et=new yo.Analytics({writeKey:s,flushAt:1}),pt(async()=>s,ts.CACHE_FN_NAME,ts.TTL,{writeKey:s})())}var yo,zf,Et,kr=I(()=>{"use strict";le();Jt();yo=require("@segment/analytics-node");ae();zf="sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY"});var Xf={};z(Xf,{isCi:()=>hs});var hs,bo=I(()=>{"use strict";hs=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Qf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Zf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:l,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Qf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:Yf(l,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);gt("test-run-ci",y)}function eg({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:w}){try{let S=Qf({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Yf(d,m),isStartUp:h,projectType:g,gridType:w,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){gt("test-run-ci-success",S);return}gt("test-run-ci-fail",{...S,failureReason:n.failureReason})}catch(S){f.error("failed to update test end analytics",{err:S})}}function tg(s){gt("batch-run-ci",s)}var Yf,Ul=I(()=>{"use strict";kr();bo();Yf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:hs&&e?"ci-with-user":hs?"ci":e?"cli-with-user":s});var Bl,de,sg=I(()=>{"use strict";Bl=class{static colorString(e,t){return`${e}${t}${Bl.Reset}`}},de=Bl;de.Reset="\x1B[0m",de.Bright="\x1B[1m",de.Dim="\x1B[2m",de.Underscore="\x1B[4m",de.Blink="\x1B[5m",de.Reverse="\x1B[7m",de.Hidden="\x1B[8m",de.FgBlack="\x1B[30m",de.FgRed="\x1B[31m",de.FgGreen="\x1B[32m",de.FgYellow="\x1B[33m",de.FgBlue="\x1B[34m",de.FgMagenta="\x1B[35m",de.FgCyan="\x1B[36m",de.FgWhite="\x1B[37m",de.FgGray="\x1B[90m",de.BgBlack="\x1B[40m",de.BgRed="\x1B[41m",de.BgGreen="\x1B[42m",de.BgYellow="\x1B[43m",de.BgBlue="\x1B[44m",de.BgMagenta="\x1B[45m",de.BgCyan="\x1B[46m",de.BgWhite="\x1B[47m",de.BgGray="\x1B[100m"});var On,jl,Yv,$l,Qv,To,wo,vo,So,Eo,Io=I(()=>{"use strict";F();ae();On=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===he.FAILED},jl=s=>{let{status:e}=s;return e===he.ABORTED},Yv=s=>{let{status:e}=s;return e===he.PASSED},$l=s=>s.runnerStatus===Kc.SKIPPED,Qv=s=>s.testStatus===et.EVALUATING,To=(s,e)=>Object.values(s).filter(t=>{var r,n;return $l(t)&&(tt(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,wo=s=>Object.values(s).filter(e=>On(e)&&Qv(e)).length,vo=s=>Object.values(s).filter(On),So=s=>Object.values(s).filter(Yv),Eo=s=>Object.values(s).filter(jl)});function eS(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Wl,Ro,Zv,xo,ng=I(()=>{"use strict";Wl=R(require("lodash"));W();Io();Ro=A("debug-reporter"),Zv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],xo=class{constructor(e){this.options=e}onTestStarted(e,t){Ro.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;Ro.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:c,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Wl.default.omit(this.options,Zv),company:Wl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let c=eS(process.argv);Ro.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,i){let o=So(e).length,a=Object.keys(e).length-o;Ro.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Vl,Ut,_n=I(()=>{"use strict";ae();Vl=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===N.DEVICE_FARM}},Ut=new Vl});var Hl={};z(Hl,{Reporter:()=>tS});var lr,Ln,Or,Co,ig,Gl,tS,ql=I(()=>{"use strict";lr=R(require("chalk")),Ln=R(require("lodash"));F();ae();_n();Io();Or={success:lr.default.green,warn:lr.default.yellow,error:lr.default.red},{CLI_MODE:Co}=Kt,ig="device",Gl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${lr.default.underline(Xe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?he.PASSED:he.FAILED,n=`(${e.testId})`,i=Or[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Gi(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=Xe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Or.error("Failed runs are:")),console.log(Or.error(t.join(`
18
- \r`)))}onTestPlanFinished(e,t,r,n,i){let o=vo(e),a=So(e),c=Eo(e),l=a.length,d=c.length,m=o.length,u="",f="";if(Ut.isTestStatusEnabled){let S=wo(e);u=` FAILED-EVALUATING: ${S}`,m-=S,f=` SKIPPED: ${To(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=Or[m?"error":"success"],w=`PASSED: ${l} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Gi(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${w} (Execution ID: ${n})`:g=`Test plan${h} completed ${w} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=Ln.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Ln.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Ln.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Ln.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let c=u=>{u.forEach((f,h)=>{var S;let g=(S=f.testData)!=null&&S.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`,w="";f.testOptimization?w=` [${f.testOptimization.reason}]`:tt(f,this.options)&&(w="-quarantine"),console.log(" ",h+1,":",`${f.name}${w}`,y,g)})},l=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Co.APPIUM?ig:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${lr.default.underline(n)} slot from ${lr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Co.APPIUM?ig:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${lr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===Co.APPIUM?"device":"browser";if(n)console.log(Or.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(Or.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===Co.APPIUM?"Appium":"Selenium";console.log(Or.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},tS=Gl});var Jl={};z(Jl,{Reporter:()=>aS});function rS(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function sS(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function nS(s){return`${s.visitedUrlsJson||""}`}async function iS(s,e,t,r,n,i){function o(u){let f=Xe(s,t,u.testId,u.resultId,r),h={$:{name:rS(u),classname:n,time:rl(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(On(u)||jl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=On(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return $l(u)&&tt(u,i)&&Ut.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=sS(u),h["visited-urls-json"]=nS(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},S={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(y),failures:d(y),timestamp:c(e)};if(Ut.isTestStatusEnabled){S.skipped=To(y,i);let b=wo(y);S.failures-=b,S["failure-evaluating"]=b}return{$:S,testcase:Object.keys(y).map(b=>o(y[b]))}}function c(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function l(u){return Object.keys(u).length}function d(u){return vo(u).length+Eo(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Kl.Builder().buildObject(m)}catch(u){return oS(u)}}function oS(s){let e=new Kl.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var Kl,og,zl,aS,Xl=I(()=>{"use strict";Kl=R(require("xml2js"));F();og=require("fs");_n();Io();zl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await iS(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await og.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};aS=zl});var ag={};z(ag,{Reporter:()=>cS});function ys(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var Yl,Ql,cS,cg=I(()=>{"use strict";W();Yl=A("team-city-reporter");Ql=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return ys(n)}onTestStarted(e,t,r,n){if(r){Yl.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,i,o){if(i){Yl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ys(t)}' details='${ys(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Yl.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ys(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ys(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ys(t)}']`)}},cS=Ql});var lg={};z(lg,{Reporter:()=>lS});var Zl,lS,ug=I(()=>{"use strict";Zl=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},lS=Zl});function Po(s){let{platform:e}=process;e==="win32"?(0,Ao.exec)(`start chrome ${s}`):e==="darwin"?(0,Ao.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,Ao.exec)(`google-chrome ${s}`)}var Ao,eu=I(()=>{"use strict";Ao=require("child_process")});var pg={};z(pg,{Reporter:()=>uS});var tu,uS,dg=I(()=>{"use strict";F();eu();tu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=Xe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Po(t)}},uS=tu});var ru,Z,Bt=I(()=>{"use strict";ng();ru=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new xo(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(ql(),Hl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Xl(),Jl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(cg(),ag)),r.includes("console")&&Promise.resolve().then(()=>(ql(),Hl)),r.includes("junit")&&Promise.resolve().then(()=>(Xl(),Jl)),r.includes("json")&&Promise.resolve().then(()=>(ug(),lg)),r.includes("chrome")&&Promise.resolve().then(()=>(dg(),pg))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,i){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var i;let n=t==null?void 0:t(...r);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||r))}}},Z=new ru});async function su(s,e,t){let r=bs[s];if(!r)return;let{slotId:n}=r;if(delete bs[s],!n){It.warn("failed to find slot slot id",{companyId:e,workerId:s});return}It.info("release slot id",{companyId:e,slotId:n});try{await iu(e,t,n)}catch(i){It.error("failed to release slot",{companyId:e,err:i})}}async function pS(s,e){let t=Object.values(bs).filter(Boolean);if(t.length!==0)try{await au(s,e,t)}catch(r){It.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}function dS(s,e){mg=global.setInterval(()=>pS(s,e),1e4)}async function mS(s,e){let t=Object.keys(bs);if(t.length){It.warn("not all slots released before end runner flow",{companyId:s});try{await oe(t,r=>su(Number(r),s,e))}catch(r){It.error("failed to release all slots",{err:r,companyId:s})}}}async function fS(s,e){await mS(s,e),clearInterval(mg)}async function gg(s,e,t){let r;try{r=await nu(s,e)}catch(n){throw It.error("failed to get slot",{companyId:s,err:n}),new Error(vt.UNKNOWN)}if(It.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw It.error("invalid response - get slot",{res:r}),new Error(vt.UNKNOWN);if(r.status==="success")return fg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new ct(vt.NOT_FOUND):r.code==="no-available-slot"?new sr("Failed to run test - concurrency limit reached"):(It.error("invalid code error response - get slot",{res:r}),new ct(vt.UNKNOWN))}async function hg(s,e,t,r){let n=bs[r];if(!n)throw new Error("slot not found");Object.assign(n,t),fg(r,n),await ou(s,e,n),It.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var It,bs,mg,fg,Dn,Ts=I(()=>{"use strict";ye();W();F();ae();Q();It=A("slot-service"),bs={},mg=null,fg=(s,e)=>{bs[s]=e};Dn={start:dS,end:fS}});function bg(s,e=process){async function t(r){await pe(oe(yg,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Mn.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(Mn.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Mn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Mn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Mn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function ws(s){yg.push(s)}var Mn,yg,Fn=I(()=>{"use strict";W();F();Mn=A("process-handler"),yg=[]});var Sg={};z(Sg,{installAllLazyDependencies:()=>bS,lazyRequire:()=>Ue});async function Ue(s,e={}){let t=dl(s);if(t)return t;let r;e.silent||(r=(0,Tg.default)(`Installing ${s} before first usage...`).start());try{let n=await yS(s);return r&&r.succeed(),n}catch(n){hS.warn("failed to install dependency lazily",{dependency:s,err:n});let i=vg(s),o=`${s}@${i}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${o}`;throw r&&r.fail(l),n}}async function yS(s){return vs.has(s)||(vs.set(s,wg(s)),vs.get(s).catch(()=>{vs.delete(s)})),vs.get(s)}async function wg(s){let e=dl(s);if(e)return e;let t=vg(s),r=`${s}@${t}`;return await no(wt(),r),ar(s)}async function bS(){let s=Object.keys(Ic);for(let e of s)await wg(e)}function vg(s){let e=Object.entries(Ic).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Tg,hS,vs,Ss=I(()=>{"use strict";Tg=R(require("ora"));ds();W();F();Pi();gn();hS=A("lazy-require"),vs=new Map});var Eg,ko,Ig=I(()=>{"use strict";Eg=require("istanbul-lib-report"),ko=class extends Eg.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var Rg,xg,Cg,Un,Rt,Ag,Oo,cu,Pg,TS,kg,Og,wS,vS,_g,SS,ES,IS,RS,xS,Lg,Dg=I(()=>{"use strict";Rg=R(require("ora")),xg=R(require("dayjs")),Cg=R(require("test-exclude")),Un=R(require("fs")),Rt=R(require("path")),Ag=R(require("istanbul-reports")),Oo=R(require("istanbul-lib-report"));ye();Q();F();W();Ss();Ig();cu=A("test-run-status"),Pg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},TS=s=>!!Pg(s).search,kg=s=>s?Pg(s).pathname.substring(1):"",Og=(s,e)=>{let t=kg(e);return!new Cg.default({relativePath:!1,include:s}).shouldInstrument(t)},wS=s=>s.substring(0,s.indexOf("?")),vS=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Ue("convert-source-map");if(t==="file"&&!e)throw new x("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},_g=(s,e)=>`${Rt.resolve(s,kg(e))}.js`,SS=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await oe(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await oe(i.sources,async(o,a)=>{if(Og(r,o))return;let c=_g(e,o);await Un.promises.mkdir(Rt.parse(c).dir,{recursive:!0}),await Un.promises.writeFile(c,i.sourcesContent[a])})})},ES={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(TS(e)&&(e=wS(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=Rt.dirname(this.getPath(s));return Rt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},IS=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=Oo.createContext({dir:t,coverageMap:e,watermarks:Oo.getDefaultWatermarks(),sourceFinder:a=>{try{let c=_g(r,a);return Un.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ko({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:ES}),Ag.create(a,c).execute(o)}),i},RS=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await Ue("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Og(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},xS=async(s,e)=>{let{mergeProcessCovs:r}=await Ue("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await uu(s,"testResult",`runId=${e}`)).data.docs;return await oe(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Bn(c,9e4);await oe(l,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await lu(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},Lg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;cu.info("start js coverage process");let n=(0,Rg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=Rt.resolve(s.codeCoverageReportPath||"./coverage"),o=Rt.resolve(i,`.js/${(0,xg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?Rt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([Ue("istanbul-lib-coverage"),xS(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}cu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),u={};await oe(l.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:w}=d.get(h),S=await vS({sourceMapType:w,source:y,sourceMapDir:a});u[h]=S;let b=await RS(s,{source:y,sourceMap:S,functions:g});m.merge(b)}),await SS(s,o,u);let f=await IS(s,m,i,o);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof x?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),cu.error(l,{err:c})}}});var Ng={};z(Ng,{SELENIUM_PERF_MARKS:()=>Oe,SeleniumPerfStats:()=>_r});var Oe,CS,_r,Es=I(()=>{"use strict";F();Oe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},CS=["ALL",...Object.values(Oe)],_r=class{constructor(){this.marks=Object.fromEntries(CS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=ne();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,Ki(r,50)],[`${t}_P95`,Ki(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Bg={};z(Bg,{initServer:()=>kS,mapFilesToLocalDrive:()=>du});function du(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,_o[t.id]?{screenshot:_o[t.id]}:{})),Object.keys(Lo).forEach(t=>{s.assets||={},s.assets[Ug[t]]=Lo[t]}),s.assets||={},s.assets.screenshots=Object.values(_o)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function kS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Ue("multer"),n=typeof t=="string"?t:AS;await pu.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(c,l,d){let m=JSON.parse(c.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=jn.join(n,m.testResultId);try{await pu.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(c,l,d){let{fileName:m}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=jn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,Fg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(_o[d.stepId]=c.file.path),d.testResultId&&PS.includes(d.subType)&&(Lo[d.subType]||=[],Lo[d.subType].push(c.file.path)),l.sendStatus(200)}),o.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>c(d.address()));function m(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new x(`Port ${s} is already in use`));default:return l(u)}}})}var pu,Mg,jn,Fg,AS,_o,Lo,Ug,PS,mu=I(()=>{"use strict";pu=R(require("fs")),Mg=R(require("os")),jn=R(require("path")),Fg=R(require("express"));Q();Ss();AS=jn.join(Mg.tmpdir(),"testim/rca/"),_o={},Lo={},Ug={"test-log":"consoleLogs","har-file":"networkLogs"},PS=Object.keys(Ug)});var ur,fu,$n,jg=I(()=>{"use strict";ur=R(require("lodash"));F();W();fu=A("override-test-data-builder"),$n=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return ur.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(e=!1){let{params:t,projectId:r}=this;return this.isObjectNotArray(t)&&t.overrideTestData!==void 0&&(this.isObjectNotArray(t.overrideTestData)&&!ur.isEmpty(t.overrideTestData)?(Object.keys(t.overrideTestData).forEach(n=>this.overrideSingleTest(n,t.overrideTestData[n])),delete t.overrideTestData):fu.error("invalid overrideTestData",{overrideTestData:t.overrideTestData,projectId:r})),this.isObjectNotArray(t)&&t.overrideAllTestsData!==void 0&&(ur.isObject(t.overrideAllTestsData)&&!ur.isEmpty(t.overrideAllTestsData)?(this.testInfoList.map(i=>i.name).forEach(i=>this.overrideSingleTest(i,t.overrideAllTestsData)),delete t.overrideAllTestsData):fu.error("invalid overrideAllTestsData",{overrideAllTestsData:t.overrideAllTestsData,projectId:r})),this.isArrayOfObjects(t)&&e&&this.testInfoList.map(i=>i.name).forEach(i=>this.overrideSingleTest(i,t)),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}fu.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return ur.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),c=r[o],l=this.createNewTestItems(c,t);return r.splice(o,a-o+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=ne();return{...e,resultId:i,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Wn(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw rt.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var pr,rt,OS,_S,LS,DS,Do,$g=I(()=>{"use strict";pr=R(require("lodash"));F();ae();fs();Ts();ye();Q();W();Bt();Fn();Dg();Es();mu();le();me();jg();_n();rt=A("test-run-status"),OS=Rr(),_S=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,LS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,DS=at();Do=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.userTestDataParams={};this.seleniumPerfStats=new _r;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData,this.userTestDataString=this.options.testDataString;let i=cn(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:_i||t.parallel||1,browser:i,gitBranch:OS,gitCommit:_S,gitRepoUrl:LS,runnerVersion:DS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:w,allLabels:S}=a,b={originalTestResultId:t,previousTestResultId:r,config:pr.cloneDeep(c),testId:l,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:w,allLabels:S},yu({projectId:n,runId:i,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,Z.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var l;let{project:n,remoteRunId:i,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Mo(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){rt.error("failed to upload test data artifact (runner)",{err:d})}let c=pr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,Lr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){var i;if(tt(e,this.options))return;let n=this.exportsGlobal;try{let o=await Wn(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token),a=Array.isArray(this.userTestDataParams)?{}:this.userTestDataParams||{},c=(i=e.config)!=null&&i.testDataPrioritized?e.config.testData:{};return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...a,...c,...this.beforeSuiteParams,...o},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw rt.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},rt.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:c,success:l}=t;if(a===et.EVALUATING&&Ut.isTestStatusEnabled){Z.onTestIgnored(e,r,`test in ${et.EVALUATING} status`);return}if(l){Z.onTestPassed(i);return}Z.onTestFailed(r,r.failureReason,Xe(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,n,c)}calcResultText(e){return e.success?he.PASSED:he.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Z.onTestIgnored(e,r,`test in ${et.QUARANTINE}`)}monitorMemoryUsage(e){let t=sl();t.isOverThreshold&&rt.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&du(o,rt),o.resultUrl=Xe(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Z.onTestFinished(o,e,i);let c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await Wn(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){rt.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await Lr(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw rt.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=Yc;return e&&(n=i),rs(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g,y;let c=e.browser?pn(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=ss(O,n)&&un(a.nativeApp)&&!e.appId,d=ir(e)&&(rs(a.nativeApp,n)||l),m=tt(a,e)||d,u={testId:a.testId,testOptimization:a.testOptimization,status:m?he.SKIPPED:he.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||et.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,testDataPrioritized:((h=a.testData)==null?void 0:h.prioritize)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((g=a.testData)==null?void 0:g.total)||null,testDataIndex:((y=a.testData)==null?void 0:y.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:c.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await Dn.end(r,t),e==="mongo"&&await Cn.end(t)}async executionStart(e,t,r,n,i){rt.info("execution started",{executionId:e,gridId:this.execConfig.gridId,gridHost:this.execConfig.gridHost,gridName:this.execConfig.gridName,gridType:this.execConfig.gridType,parallel:this.execConfig.parallel,runnerVersion:this.execConfig.runnerVersion,source:this.execConfig.source});let{options:o}=this,{remoteRunId:a,projectData:c,company:{companyId:l}={},slotService:d}=o;ws(()=>Promise.all([this.endKeepAlive(d,t,l),No("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...O.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=this.userTestDataString,f=await Wn(new Function(u||""));if(f&&(this.userTestDataParams=f,Array.isArray(f))){let T=new $n(f,pr.cloneDeep(this.testInfoList),t);this.testInfoList=T.overrideTestData(!0)}let h=await Wn(o.beforeSuite,m),g=new $n(h,pr.cloneDeep(this.testInfoList),t);this.testInfoList=g.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=h;let{testInfoList:y}=this,w=[],S=[],b=[];for(let T of y){if(T.isBeforeTestPlan){w.push(T);continue}if(T.isAfterTestPlan){b.push(T);continue}S.push(T)}let v=async()=>{let T=pr.cloneDeep(this.testRunStatus);await oe(Object.keys(T),async B=>{var j;let G=T[B],E=(j=G.config)==null?void 0:j.testData,k=G.testId,D=await Mo(t,k,B,E,c.defaults);D&&(delete G.config.testData,G.config.testDataUrl=D)});let C=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),_=hu({executionId:e,projectId:t,labels:n||[],startTime:r,executions:T,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:C,intersections:o.intersections});return this.executionStartedPromise=_,_.catch(B=>rt.error(B)),_};try{await v()}catch(T){rt.error("Failed to start suite",{err:T}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:w,tests:S,afterTests:b}}concatSeleniumPerfMarks(e){pr.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=cl(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===he.PASSED&&n++,m===he.SKIPPED&&i++,m===he.FAILED&&u===et.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await Wn(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),rt.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Lg(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await No("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw rt.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await gu(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function bu(s){var i;let e=s.canary?"-master.zip":".zip",t=`${tr}/testim-headless${e}`,r=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(i=s.company)==null?void 0:i.companyId,projectId:s.project,runnerEnvironment:Xs});return r||(NS.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),r=`${tr}/testim-headless.zip`),!(s.ext||s.extensionPath)&&r&&(t=r,s.testimHeadlessExtensionDownloadUrl=r),{chrome:t,"edge-chromium":t}}function Wg(s){let{chrome:e}=bu(s);return e}function Fo(s){let e=`${tr}/sessionPlayer`;return s.canary?`${e}-master`:e}var NS,Vn=I(()=>{"use strict";le();me();W();NS=A("runOptionsUtils")});function Is(s){var n;let t=(n=new RegExp(`^\\b(${Object.values(Tu).join("|")})`).exec(s))==null?void 0:n[0];return t||Tu[Gd]||"usw2"}var Tu,Gg,Uo=I(()=>{"use strict";le();Tu={"us-west-2":"usw2","eu-central-1":"euc1"},Gg=Object.fromEntries(Object.entries(Tu).map(([s,e])=>[e,s]))});function Hg(s,e){if(e){if(!$S.has(e)){Gn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var qg,zg,Xt,Kg,Jg,Xg,Bo,Yg,Gn,MS,FS,Hn,US,BS,jS,ce,$S,jo=I(()=>{"use strict";qg=R(require("ms")),zg=R(require("p-retry")),Xt=R(require("node:os")),Kg=R(require("portfinder")),Jg=R(require("node:child_process"));F();qe();ye();Xg=R(require("node:fs")),Bo=R(require("node:fs/promises")),Yg=require("node:path");Q();W();Vn();ae();me();F();Uo();Gn=A("lambdatestService"),MS="https://downloads.lambdatest.com/tunnel/v3",FS={win32ia32:"windows/32bit/LT_Windows.zip",win32x64:"windows/64bit/LT_Windows.zip",darwinia32:"mac/32bit/LT_Mac.zip",darwinx64:"mac/64bit/LT_Mac.zip",darwinarm64:"mac/64bit/LT_Mac.zip",linuxia32:"linux/32bit/LT_Linux.zip",linuxx64:"linux/64bit/LT_Linux.zip",freebsdia32:"freebsd/32bit/LT_Freebsd.zip",freebsdx64:"freebsd/64bit/LT_Freebsd.zip"},Hn=`${Xt.tmpdir()}/LT`,US=`${Hn}/LT`,BS=(0,qg.default)("15m"),jS="2560x1440",ce=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===N.TESTIM_LAMBDATEST||e.type===N.LAMBDATEST||e.type===N.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t,r){ce.isLambdatestGrid(e)&&(ce.lambdatestConfigPromise||=wu(t,r),ce.lambdatestConfig=await ce.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?BS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await Te(US))return;let t=FS[Xt.platform()+Xt.arch()];if(!t)throw new Error(`tunnel on ${Xt.platform()+Xt.arch()} platform is not supported.`);let r=`${Hn}.zip`;await Qe(`${MS}/${t}`,r),await Ze(r,Hn)}static async chmodLtTunnel(e){if(!(Xt.platform()==="win32"||!await Te(e))){try{await Bo.access(e,Xg.constants.X_OK);return}catch{}try{await Bo.chmod(e,"777")}catch(r){throw Gn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ie(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ce.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Kg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;ce.tunnelName=ne();let l=["--tunnelName",ce.tunnelName,"--infoAPIPort",String(t)];if(O.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],o&&a)l=[...l,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(O.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(l=[...l,...tl(u)])}if(O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)l=[...l,"--user",n,"--key",i];else throw new x("tunnel requires username and password");if(c)try{let u=new URL(c);l=[...l,"--proxy-host",u.hostname],u.port&&(l=[...l,"--proxy-port",u.port]),u.username&&u.password&&(l=[...l,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new x("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await ce.delay(3e3),await ce.chmodLtTunnel((0,Yg.join)(Hn,"LT")),ce.tunnel=Jg.spawn("./LT",l,{cwd:Hn});let d="",m="";ce.tunnel.stdout.on("data",u=>{d+=u.toString()}),ce.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,zg.default)(()=>ve(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Gn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),Gn.error("Failed to start LT tunnel",{err:u}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ce.tunnel))return new Promise((t,r)=>{ce.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ce.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,c){var T;if(!this.isActive)return{};let l=ce.lambdatestConfig.CAPABILITIES[t]||{},d={...ce.tunnelName&&{tunnel:!0,tunnelName:ce.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:Hg(n,a==null?void 0:a.os)||Hg(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||l.platform||ce.lambdatestConfig.PLATFORM,resolution:ce.lambdatestConfig.RESOLUTION??jS,...t!=="safari"&&{version:l.version}};if(c!==J.APPIUM&&c!==J.SELENIUM&&!f){let C=bu({canary:u});!h&&C[t]&&(m=[...m,C[t]]),h&&Me(h)&&(m=[...m,h]),m.length||Gn.warn("No extension was loaded in LambdaTestService",{extUrls:C,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&Me(g)&&(m=[...m,g]);let w=Is(e.project||""),b={euc1:"eu"}[w],v=b?{region:b}:{};return{build:r,name:`${n} - ${i}`,...v,selenium_version:ce.lambdatestConfig.SELENIUM_VERSION,timezone:ce.lambdatestConfig.TIMEZONE,...l,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},$S=new Set(["Linux","Windows 10","Windows 11","MacOS Tahoe","MacOS Sequoia","macOS Sonoma","macOS Ventura","macOS Monterey","macOS Catalina","macOS Big Sur","macOS Mojave","macOS High Sierra","macOS Sierra","OS X El Capitan","OS X Yosemite","OS X Mountain Lion"])});var Qg,WS,$o,vu=I(()=>{"use strict";Q();Qg=["platformName","platform","app","bundleId","appPackage","extensions"],WS=["selenium_version","protocol","host","port","path","build"],$o=(s,e)=>{let t=e==="lambdaTest"?[...Qg,...WS]:Qg,r=[],n=[s];for(;n.length;){let i=n.pop();for(let[o,a]of Object.entries(i))t.includes(o)&&r.push(o),a&&typeof a=="object"&&n.push(a)}if(r.length)throw new x(`Custom capabilities contains forbidden keys: ${r.join(", ")}`)}});function GS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function lh(s){return nh.readFileSync(s,{encoding:"base64"})}function uh(s,e,t,r){if(t!=null&&t.isLambdatestRun()&&Me(s))return null;if(s){if(r)return s.endsWith(".zip")?(Ze(s,th),th):s;let n=lh(s);xs.info(`adding extension: custom, path: ${s} length: ${n.length} hash: ${Iu(n)} current extension count: ${e.length}`),e.push(n)}return null}function ph(s,e,t,r,n,i){if(n!=null&&n.isLambdatestRun())return null;let o=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!o){let m=typeof s.ext=="string"?s.ext:`${__dirname}/..`,u=r||m,f=`--load-extension=${u}`;return xs.info(`adding extension: testim unpacked , path: ${u}`),t.push(f),null}let c=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&o&&(c=Dr.basename(o));let l=Dr.join(process.cwd(),c);if(i)return Ze(l,eh),eh;let d=lh(l);return xs.info(`adding extension: testim zipped, path: ${l} length: ${d.length} hash: ${Iu(d)} current extension count: ${e.length}`),e.push(d),null}function HS(s,e,t,r,n,i,o,a){var g,y;let c=t.seleniumName||t.browserValue,l=[],d=[...ah];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Su.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Su.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1,"profile.password_manager_leak_detection":!1},w3c:!0};if(Eu(n)){let w=O.flags.DFAcceptInsecureOrigins.getValue();typeof w=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${w}`),m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}Eu(n)&&c==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(w=>d.push(`--${w}`));try{let w=Wo();w.length&&w.forEach(S=>d.push(`--disable-features=${S}`))}catch{}e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Su.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:c});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Jc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),uh(r,l,o),a===J.EXTENSION&&ph(e,l,d,i,o),l.length>0&&(m.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[c],h={MicrosoftEdge:"ms",chrome:"goog"}[c];return ce.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function zS(s,e,t){let r={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":rh.join(","),"browser.helperApps.neverAsk.openFile":rh.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function Rs(s){return`${s.width}x${s.height}`}function ZS(s){let{platform:e}=s;if(!e)return Rs(sh);let t=e.split(" ")[1];return e.startsWith("Windows")&&QS.has(t)?Rs(JS):e==="Linux"?Rs(KS):e.startsWith("macOS")?Rs(XS):Rs(e==="OS X El Capitan"||e==="OS X Yosemite"?YS:sh)}function eE(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(n["sauce:options"].screenResolution=ZS(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let i=(0,oh.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,st.merge(i,n,r)}return st.merge(n,r)}return{}}function tE(s){let{runnerOptions:e}=s;if(st.isEmpty(e.browserstack))return{};let{projectData:t,testRunConfig:r,testId:n,testName:i,executionId:o,executionName:a}=s,c={buildName:`${a} - ${o}`,sessionName:`${i} - ${n}`,projectName:`${t.name} - ${t.projectId}`,...e.browserstack};return r&&r.browserValue==="safari"&&r.bs.safari_version&&(c.os_version=r.bs.safari_version,r.bs.safari_version==="10"&&Object.assign(c,{"safari.options":{technologyPreview:!0}})),c}function rE(s){return s.perfecto?s.perfecto:{}}function sE(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function nE(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,i=r||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=vc(i,o)),a}function Wo(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function Vo(s){var B,G,E,k;let{overrideConfiguration:e,browserOptions:t,testId:r,testName:n,testRunConfig:i,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:d,testResultId:m,lambdatestService:u,mode:f,customCapabilities:h,useLocalChromeDriver:g}=s;if(o.mode==="local"){let D=[],j=[...ah],V={};t.headless&&j.push("--headless"),t.silentDebuggerExtensionApi&&j.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&j.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let re=Wo();re.length&&re.forEach(ge=>j.push(`--disable-features=${ge}`))}catch{}t.chromeExtraArgs&&t.chromeExtraArgs.forEach(re=>j.push(`--${re}`)),t.chromeBinaryLocation&&(V.binary=t.chromeBinaryLocation);let K,q=null;return f!==J.SELENIUM&&(K=ph(t,D,j,null,u,g)),q=uh(a,D,u,g),g&&j.push("--enable-unsafe-extension-debugging","--remote-debugging-pipe"),{logLevel:Zg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:j,extensions:D,...V},browserName:"chrome",...g&&{webSocketUrl:!0}},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515,...g&&K&&{unzippedTestimExtensionPath:K},...g&&q&&{unzippedCustomExtensionPath:q}}}let{driverRequestTimeout:y,driverRequestRetries:w}=t,S=nE(t,o),b={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Zg,connectionRetryTimeout:y,connectionRetryCount:w,getSessionTimeout:Math.max(u.getSessionTimeout,t.getSessionTimeout),getSessionRetries:u.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!st.isEmpty(S)&&{headers:S},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Eu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,b.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(b.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let v=Number(t.browserTimeout/1e3),T=t.browser||(i==null?void 0:i.browserValue),C={runnerOptions:t,testId:r,testName:n,testRunConfig:i,executionId:c,executionName:l,projectData:d};st.merge(b.desiredCapabilities,eE(t,n,i),tE(C),rE(t),sE(t,T,v),u==null?void 0:u.getCapabilities(t,T,c,m,n,i,e,f));let _=null;switch(!t.ext&&!t.extensionPath&&((B=o.host)!=null&&B.endsWith(".testim.io"))&&!t.canary&&f===J.EXTENSION&&(T==="chrome"||T==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(_="/opt/testim-headless"),T){case"chrome":case"edge-chromium":b=qS(b,t,i,a,o,_,u,f);break;case"firefox":b=zS(b,t,u);break;case"safari":case"safari technology preview":b=GS(b,T);break;default:break}h?($o(h,o.type),st.merge(b.desiredCapabilities,h)):st.merge(b.desiredCapabilities,t.seleniumCapsFileContent);try{let D={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},j=re=>re[o.provider]||re[b.host]||re[D[b.host]],V=re=>{var ge,Ke;return j(re)||re[(ge=b.desiredCapabilities)==null?void 0:ge.browserName]||re[(Ke=b.desiredCapabilities)==null?void 0:Ke.version]||re||{}},K=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),q=V(V(K));Object.keys(q).length&&(xs.info(`Adding custom capabilities: ${JSON.stringify(q)}`),Object.assign(b.desiredCapabilities,q))}catch(D){xs.error("Failed to load custom capabilities",{error:D,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(b.desiredCapabilities&&!b.capabilities&&(VS(b),b.capabilities={alwaysMatch:b.desiredCapabilities,firstMatch:[{}]},delete b.desiredCapabilities),b.hostname=b.host,s.printFinalCaps){let D=(G=b.capabilities)==null?void 0:G.alwaysMatch,j=JSON.parse(JSON.stringify(b)),V=(E=j==null?void 0:j.capabilities)==null?void 0:E.alwaysMatch,K=re=>re.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(re=>{var ge,Ke;V!=null&&V[re]&&(V[re].extensions=(Ke=(ge=D==null?void 0:D[re])==null?void 0:ge.extensions)==null?void 0:Ke.map(K))}),V!=null&&V.loadExtension&&(V.loadExtension=(k=D==null?void 0:D.loadExtension)==null?void 0:k.map(K));let q=require("node:util");console.log(q.inspect(j,{showHidden:!1,depth:null,colors:!0}))}return b}var nh,Dr,ih,st,oh,xs,Zg,Su,ah,ch,eh,th,Iu,Eu,VS,qS,rh,sh,KS,JS,XS,YS,QS,Go=I(()=>{"use strict";nh=R(require("node:fs")),Dr=R(require("node:path")),ih=R(require("node:crypto")),st=R(require("lodash"));F();le();W();zc();F();me();ae();jo();vu();oh=require("lodash"),xs=A("testim-desired-capabilities-builder"),Zg=Oi?"debug":"silent",Su={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},ah=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],ch=Dr.join(St,"extensions"),eh=Dr.join(ch,"testim-headless"),th=Dr.join(ch,"custom-extension"),Iu=(...s)=>ih.createHash("sha256").update(s.join("")).digest("hex"),Eu=s=>s.type===N.DEVICE_FARM||s.type===N.HYBRID&&s.provider==="devicefarm",VS=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=O.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{xs.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};qS=st.memoize(HS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(st.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return Iu(o,a,c,r,l,i)}),rh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];sh={width:1920,height:1080},KS={width:1920,height:1200},JS={width:2560,height:1600},XS={width:2360,height:1770},YS={width:2048,height:1536},QS=new Set(["7","8","8.1","10","11"])});function je(s){var e,t,r,n,i,o,a,c;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||((t=s.message)==null?void 0:t.toLowerCase())==="unknown error"||((r=s.message)==null?void 0:r.match(/Unknown timeout type/))||s.name==="unknown command"||((n=s.message)==null?void 0:n.match(/did not match a known command/))||((i=s.message)==null?void 0:i.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=s.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((c=s.message)==null?void 0:c.match(/\.\w* is not a function/))}function mh(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var Ru=I(()=>{"use strict"});function xu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function i(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return i(y,f)}function o(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=i(u,"stroke-width");return!!g&&parseInt(g,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(u){return i(u,"overflow")==="hidden"}function c(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:c(f))}function l(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:l(u.parentNode):!1}if(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return xu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||c(s))}var fh=I(()=>{"use strict"});var gh,hh,Yt,iE,oE,Ho,yh=I(()=>{"use strict";gh=R(require("promise-queue")),hh=R(require("webdriverio"));le();Ve();F();W();Kr();fh();Ru();Es();Yt=A("WebDriverApi"),iE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},oE={implicit:0,pageLoad:1,script:2},Ho=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,i=t?t.toString().slice(0,2e3):"";throw Yt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Rc!==void 0&&(e=Rc);let t=1/0;this.queue=new gh.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async installExtensions(e){var r;let t=[e==null?void 0:e.unzippedTestimExtensionPath,e==null?void 0:e.unzippedCustomExtensionPath].filter(Boolean);for(let n of t)await((r=this.client)==null?void 0:r.send({method:"webExtension.install",params:{extensionData:{type:"path",path:n}}}))}async initClient(e,t,r,n,i){var c,l,d,m,u,f,h,g;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let o=((c=e.capabilities.alwaysMatch)==null?void 0:c.loadExtension)||((l=e.capabilities.alwaysMatch)==null?void 0:l.loadExt)||((f=(u=(m=(d=e.capabilities.alwaysMatch)==null?void 0:d["goog:chromeOptions"])==null?void 0:m.extensions)==null?void 0:u[0])==null?void 0:f.slice(0,80)),a=(h=this.seleniumPerfStats)==null?void 0:h.markStart(Oe.GET_BROWSER);try{await this.addToQueue(async()=>{Yt.info("requesting browser",{testResultId:r,testName:t,extUrl:o}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await hh.remote(e),n&&await this.installExtensions(i),this.logGridStatus(r)}),M("after client init")}finally{(g=this.seleniumPerfStats)==null||g.markEnd(a,Oe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){Yt.info("grid status is not supported by the grid",{testResultId:e});return}Yt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Yt.info("grid status",{gridStatusMsg:i.message,ready:i.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){Yt.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await o()}catch(a){if(je(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(je(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Oe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,Oe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Oe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Fe(e)))}finally{this.seleniumPerfStats.markEnd(t,Oe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(xu,{ELEMENT:e,[er]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(je(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(mh(e,this.isSafari(),Yt))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let i=[];return i[oE[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(je(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Fe(e)),await this.elementIdValue(Fe(e),t)}async getViewportSize(e){let t=await this.execute(iE);if(typeof e=="string"&&/(width|height)/.test(e)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Fe(e))})}submitFormManually(e){return this.addToQueue(async()=>{var i;let t=await((i=this.client)==null?void 0:i.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let i=await this.client.$(e);await this.client.action("pointer").move({origin:i}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,o),n=async()=>await this.client._setWindowSize(i,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(i){if(je(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Yt.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Yt.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var dr={};z(dr,{getSessionPlayer:()=>ee,options:()=>Au});var qo,Au,Cu,ee,Se=I(()=>{"use strict";qo=require("path");W();Au={playerPath:void 0},ee=()=>{if(Cu)return Cu;let s=(Ve(),Je(We));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Tn(),Je(bn)),t=e(),r=Au.playerPath?(0,qo.resolve)(Au.playerPath,"src/background/sessionPlayerInit.ts"):(0,qo.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),Cu=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(fm),n}});var bh={};z(bh,{doubleClick:()=>aE});var aE,Th=I(()=>{"use strict";aE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function f(S,b,v){return v>S&&v<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,w=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:w}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},l=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?c(h,f.x,f.y):l(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var qn={};z(qn,{dispatchFocus:()=>cE});function cE(s,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function r(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let i=getLocatedElement(s);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var zn=I(()=>{"use strict"});var Ih={};z(Ih,{WebDriver:()=>Fr});async function dE(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await uE(r):void 0}catch(r){$e.info("Error getting cdpAddress",r);return}}var Cs,Sh,Eh,$e,mr,lE,wh,uE,Nr,pE,vh,Mr,Fr,Kn=I(()=>{"use strict";Cs=R(require("lodash"));F();Ve();Go();Sh=R(require("p-retry")),Eh=R(require("ua-parser-js"));Kr();W();Ru();yh();Q();me();Es();$e=A("webdriver"),[mr,lE]=[0,2],{extractElementId:wh,getCdpAddressForHost:uE}=X,Nr=()=>(Se(),Je(dr)).getSessionPlayer().codeSnippets,pE=()=>(Se(),Je(dr)).getSessionPlayer().locatorBuilderUtils,vh=()=>(Se(),Je(dr)).getSessionPlayer().utils,Mr=()=>(Se(),Je(dr)).getSessionPlayer().positionUtils;Fr=class extends Ho{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.keepAliveFailedCallbacks=[];this.generalKeepAliveFailures=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null)}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}registerToKeepAliveFailed(t){this.keepAliveFailedCallbacks.push(t)}unregisterToKeepAliveFailed(t){this.keepAliveFailedCallbacks=this.keepAliveFailedCallbacks.filter(r=>r!==t)}async init(t){var B,G,E,k,D,j,V,K;let{projectData:r,overrideConfiguration:n,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:u,testResultId:f,seleniumPerfStats:h,fastInit:g,lambdatestService:y,printFinalCaps:w,mode:S,customCapabilities:b,useLocalChromeDriver:v}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((E=(G=(B=i==null?void 0:i.company)==null?void 0:B.activePlan)==null?void 0:G.premiumFeatures)==null?void 0:E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let T=Vo({projectData:r,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:u,testResultId:f,lambdatestService:y,overrideConfiguration:n,printFinalCaps:w,mode:S,customCapabilities:b,useLocalChromeDriver:v});T.desiredCapabilities&&delete T.desiredCapabilities.marionette,T.capabilities&&delete T.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(y==null?void 0:y.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=h;let C=g?0:1500,_=g?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let q={unzippedTestimExtensionPath:T.unzippedTestimExtensionPath,unzippedCustomExtensionPath:T.unzippedCustomExtensionPath},re=await this.initClient(T,a,f,v,q);M("after initResult before getCdpAddress in init"),this.cdpUrl=await dE(re),M("after getCdpAddress in webdriver.js init"),$e.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await ie(C),O.flags.dontFocusOnInit.isEnabled()||await _(),M("after focus and delay in webdriver.js init")}catch(q){let re=JSON.stringify(Cs.omit(T,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));$e.error("failed to init webdriver",{err:q,capabilitiesAsString:re});let ge=((D=(k=i==null?void 0:i.company)==null?void 0:k.activePlan)==null?void 0:D.plan)==="free";throw(j=q.stack)!=null&&j.includes("at startWebDriverSession")&&((V=q.message)!=null&&V.startsWith("Failed to create session"))&&((K=q.message)!=null&&K.includes("Timeout awaiting 'request'"))&&ge?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(q.message)?new Xr(q.message):/capabilit(y|ies)/.test(q.message)?new Mi(q.message):/403 Forbidden/.test(q.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(q.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${q.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>Cs.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=ne();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,$e.warn("close unexpected alert open"),await this.alertAccept().catch(c=>$e.warn("failed to click on alert",{err:c}));return}if($e.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;$e.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.handleThresholdBasedError(this.browserClosedCallbacks,a)}else this.generalKeepAliveFailures++,this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures>=3&&this.handleThresholdBasedError(this.keepAliveFailedCallbacks,a)}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}handleThresholdBasedError(t,r){t.forEach(n=>{try{n(r)}catch{}})}async switchToLocatedFrame(t){let r=await this.getElement(t),n=wh(r.value);return await this.switchToFrame({ELEMENT:n,[er]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new Fi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(Oe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Oe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
19
- var fn = ${Nr().getLocatedElementCode};
17
+ 4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),o}}async function Lv(){let s=`${tr}/sessionPlayer_LATEST_RELEASE`;return(await Kt(s)).body.toString("utf8")}async function Dv(s,e){if(!Me(s)||Me(s)&&e||We)return s;let t=await Lv();return`${s}-${t}`}function vl(){let s=Tt();return ps.resolve(s,"testim-bin")}function Nv(){let s=vl();return ps.resolve(s,"sessionPlayer.zip")}async function kf(s,e,t=!1){try{return await $i(s,e),await Qe(e,vl())}catch(r){if(t)throw r;return await kf(s,e,!0)}}async function xr(s,e){oo.info("prepare player",{location:s,canary:e});let t=Nv();return ut(async()=>{let r=await Dv(s,e);return await kf(r,t),{}},"preparePlayer",Pf,[s,e,t])()}var xf,Cf,ps,Af,oo,Pf,bl,Rf,bn=I(()=>{"use strict";xf=R(require("ms")),Cf=R(require("node:fs")),ps=R(require("node:path"));ue();Xt();Af=require("serialize-error");W();pl();Q();F();oo=A("prepare runner and testim start"),Pf=(0,xf.default)("0.5 day"),bl=16,Rf=`The size of the custom extension is more than ${bl}MB`});function Mv(){let s=Tn.type().toLowerCase();return s==="darwin"?Tn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?Tn.arch()==="x64"?"win64":"win32":"linux"}async function co(){let s=Mv(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new x(`Unsupported platform: ${s}`);let r=parseInt(wn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},i={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},o=`${e}/${t[s]}/${wn}/${n[s]}.zip`,a=ao.join(Sl,n[s]),c=`${a}.zip`,l=ao.join(a,i[s]);if(await Te(l))return l;if(!await Te(c)){let m=(0,El.default)("Downloading Chromium").start();try{await Of.promises.mkdir(Sl),await Ye(o,c)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,El.default)("Extracting Chromium").start();try{await Qe(c,Sl)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),l}var Of,Tn,ao,El,wn,Sl,Il=I(()=>{"use strict";Of=R(require("fs")),Tn=R(require("os")),ao=R(require("path")),El=R(require("ora"));Q();F();wn="1000968",Sl=ao.join(vt,`chrome-${wn}`)});async function Df(s,e){return Cr=s,Al=e,await Rl()}function Nf(s,e){Cr=e.projectId,Al=e.token,vn=e.userAccessKey,pt=s.token,En=Pl(pt),In=s.refreshToken,xl=s.ngrokToken,Cl=s.isNgrokWhitelisted,_f=e.publicIp,Lf=e.initializedFromCache}function Uv(s=Cr,e=Al){return ut(()=>(Sn.info("request to get cli token from server"),Ve({url:`${be()}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Fv*10,{projectId:s,token:e})()}async function Bv(){Sn.info("request to refresh JWT cli token from server");let s=await Ve({url:`${be()}/auth/refreshToken`,body:{token:pt,refreshToken:In}});return pt=s.token,En=Pl(pt),s.refreshToken&&(In=s.refreshToken),pt}async function Rl(){try{let s=await Uv();return Sn.info("successfully get cli token from server"),pt=s.token,En=Pl(pt),In=s.refreshToken,xl=s.ngrokToken,Cl=s.isNgrokWhitelisted,pt}catch(s){throw s.message.includes("Unauthorized")?new x("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(Sn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Cr}),new x(`While trying to retrieve CLI token, caught error: ${s}`))}}function Pl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Mt(){if(!En)return Rl();let s=O.flags.accessTokenExpiryMargin.getValue();if(En<Date.now()+4*s)try{return await Bv()}catch(e){return Sn.error("failed to refresh token, executing fallback",e),Rl()}return pt}function lo(){return In}function Ar(){return pt?{uid:require("jsonwebtoken").decode(pt).id,ngrokToken:xl,isNgrokWhitelisted:Cl}:{}}async function uo(){if(!vn||!Cr)return;if(await kl({userAccessKey:vn,projectId:Cr}))return vn;let e=`user access key "${vn}" is invalid for project "${Cr}"`;throw new x(e)}function po(){return _f}function mo(){return Lf}var Sn,pt,En,In,xl,Cl,Cr,Al,vn,_f,Lf,Fv,dt=I(()=>{"use strict";ue();Ge();Xt();Q();W();ye();me();Sn=A("testim-custom-token"),Cr=null,Al=null,Fv=5*60*1e3});function jv(s){if(s.protocol)return s.protocol;if([N.TESTIM_PRIVATE,N.TESTIM,N.BROWSERSTACK,N.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([N.TESTIM_ENTERPRISE,N.TESTIM_LAMBDATEST,N.DEVICE_FARM].includes(s.type)){let e=Mf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function $v(s){let e=Mf.exec(s);return e==null?void 0:e[3]}function go(s){var v,T,C,_,B,G,E,k,D,j,V;let e=s&&$v(s.host),t=s.port,r=s.path,n=s&&jv(s),i=s.token,o=s.slotId,a=(v=s.hybrid)==null?void 0:v.tunnel,c=(T=s.external)==null?void 0:T.user,l=(C=s.external)==null?void 0:C.key,d=s.type,m=d===N.HYBRID?a&&((G=(B=(_=s.hybrid)==null?void 0:_.external)==null?void 0:B[s.hybrid.tunnel])==null?void 0:G.user):c,u=d===N.HYBRID?a&&((D=(k=(E=s.hybrid)==null?void 0:E.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:D.key):l,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(j=s.mobileTokens)==null?void 0:j.androidToken,w=(V=s.mobileTokens)==null?void 0:V.iosToken,S=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:c,key:l,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:w,apiUrl:S,isSupportGrid:b}}async function Vv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(c){throw mt.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(wt.UNKNOWN)}if(mt.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw mt.error("invalid response - get grid",{res:o}),new Error(wt.UNKNOWN);if(o.status==="success"){if(o.grid.mode==="local")return{mode:"local"};((a=o.grid)==null?void 0:a.mode)==="custom"&&Object.assign(o.grid,jf(n));let c=go(o.grid);return Wv(t,e,c.gridId,c.slotId,r,c.isSupportGrid),c}throw o.code==="not-found"?new at(wt.NOT_FOUND):o.code==="no-available-slot"?new sr(`Failed to run test on ${r} - concurrency limit reached`):(mt.error("invalid code error response - get grid",{res:o}),new at(wt.UNKNOWN))}function Uf(s){return Ml(s)}async function Bf(s,e,t){let n=(t||await Uf(s)).find(i=>i._id===e);if(!n)throw new x(`Failed to find grid id: ${e}`);return go(n)}async function Gv(s,e,t){let n=(t||await Uf(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new x(`Failed to find grid name: ${e}`);return go(n)}async function Ol(s,e){let t=Rn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete Rn[s],!a){if(!r){mt.warn("failed to find grid slot id",{projectId:e});return}mt.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await Ll(o,e,r,n,i)}catch(c){mt.error("failed to release slot",{projectId:e,err:c})}}}async function Hv(s){let e=Object.values(Rn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid)try{await _l(s,e)}catch(t){mt.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}function qv(s){Ff=global.setInterval(Hv,1e4,s)}async function zv(s){let e=Object.keys(Rn);if(e.length){mt.warn("not all slots released before end runner flow",{projectId:s});try{await oe(e,t=>Ol(Number(t),s))}catch(t){mt.error("failed to release all slots",{err:t,projectId:s})}}}async function Kv(s){await zv(s),clearInterval(Ff)}function Jv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function Xv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function jf(s){let t=(()=>fo.isEmpty(s.testobjectSauce)?fo.isEmpty(s.saucelabs)?fo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=Jv(t,s),c=Xv(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:c,key:a,gridId:ne()}}async function $f(s,e){let t=s.company.companyId;return await Bf(t,e.gridId,s.allGrids)}async function Wf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:c}=s;if(n||o||i)return{mode:"local"};if(r)return jf(s);let l=t==null?void 0:t.companyId;if(a)return Bf(l,a,e);if(c)return Gv(l,c,e);if(cn(s)||s.tunnelOnlyMode){mt.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new at("Missing host or grid configuration")}async function Vf(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:c,localTmaUrl:l,useLocalChromeDriver:d,useChromeLauncher:m,company:u}=t,f=Boolean(d||m||l),h=u==null?void 0:u.companyId;return Vv(o,h,r,s,t,()=>Nl({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:i,testResultId:n}))}var fo,mt,Rn,Mf,Ff,Wv,xn,Gf,ds=I(()=>{"use strict";fo=R(require("lodash"));ye();W();F();ae();Q();mt=A("grid-service"),Rn={},Mf=/(^(https?):\/{2})?(.*)/,Ff=null;Wv=(s,e,t,r,n,i)=>{Rn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};xn={start:qv,end:Kv};Gf=async(s={},e={},t={},r={},n={})=>{var g,y,w;let{company:{companyId:i}={},project:o}=s,{gridId:a,type:c}=e,l=s.browser||t.browserValue,d=Boolean(s.tunnel),{maxRetries:m,currentRetry:u}=n;if(!a||!c||((c===N.TESTIM_LAMBDATEST||c===N.LAMBDATEST)&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e,i,o)),c!==N.HYBRID||!i||!l||!m||!u))return e;let f=await Dl({companyId:i,gridId:a,maxRetries:m,currentRetry:u,browser:l,usingTunnel:d});mt.info("handling hybrid grid",{response:f,companyId:i});let h=go({...e,...f.connectionDetails,provider:f.provider});return f.provider!=="lambdatest"&&((y=r.disable)==null||y.call(r)),f.provider==="lambdatest"&&await((w=r.enableIfNeeded)==null?void 0:w.call(r,h,i,o)),h}});function An(){return ho||"master"}function Hf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){ho="master";return}if(s!=null&&s.isArchived)throw new x(`Branch ${s.branch} is archived, run aborted.`);if(s){ho=s.branch||s;return}ho=e?"master":void 0}var ho,Fl=I(()=>{"use strict";Q()});function Kf(s){if(!We){if(s!=null&&s.userId||(s={anonymousId:"runnerId"}),!St){os(Zr.CACHE_FN_NAME).then(e=>{St=new yo.Analytics({writeKey:e||zf,flushAt:1}),St.identify(s)});return}St.identify(s)}}function ft(s,e){return ms("ci",s,e)}function ms(s,e,t){if(We)return;let r=s?{userId:s}:{anonymousId:"runnerId"};if(!St){os(Zr.CACHE_FN_NAME).then(n=>{St=new yo.Analytics({writeKey:n||zf,flushAt:1}),St==null||St.track(Object.assign(r,{event:e,properties:t}))});return}St.track(Object.assign(r,{event:e,properties:t}))}function Jf(s){s&&(St=new yo.Analytics({writeKey:s,flushAt:1}),ut(async()=>s,Zr.CACHE_FN_NAME,Zr.TTL,{writeKey:s})())}var yo,zf,St,Pr=I(()=>{"use strict";ue();Xt();yo=require("@segment/analytics-node");ae();zf="sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY"});var Xf={};z(Xf,{isCi:()=>fs});var fs,bo=I(()=>{"use strict";fs=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Qf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Zf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:l,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Qf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:Yf(l,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);ft("test-run-ci",y)}function eg({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:w}){try{let S=Qf({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Yf(d,m),isStartUp:h,projectType:g,gridType:w,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){ft("test-run-ci-success",S);return}ft("test-run-ci-fail",{...S,failureReason:n.failureReason})}catch(S){f.error("failed to update test end analytics",{err:S})}}function tg(s){ft("batch-run-ci",s)}var Yf,Ul=I(()=>{"use strict";Pr();bo();Yf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:fs&&e?"ci-with-user":fs?"ci":e?"cli-with-user":s});var Bl,de,sg=I(()=>{"use strict";Bl=class{static colorString(e,t){return`${e}${t}${Bl.Reset}`}},de=Bl;de.Reset="\x1B[0m",de.Bright="\x1B[1m",de.Dim="\x1B[2m",de.Underscore="\x1B[4m",de.Blink="\x1B[5m",de.Reverse="\x1B[7m",de.Hidden="\x1B[8m",de.FgBlack="\x1B[30m",de.FgRed="\x1B[31m",de.FgGreen="\x1B[32m",de.FgYellow="\x1B[33m",de.FgBlue="\x1B[34m",de.FgMagenta="\x1B[35m",de.FgCyan="\x1B[36m",de.FgWhite="\x1B[37m",de.FgGray="\x1B[90m",de.BgBlack="\x1B[40m",de.BgRed="\x1B[41m",de.BgGreen="\x1B[42m",de.BgYellow="\x1B[43m",de.BgBlue="\x1B[44m",de.BgMagenta="\x1B[45m",de.BgCyan="\x1B[46m",de.BgWhite="\x1B[47m",de.BgGray="\x1B[100m"});var kn,jl,Yv,$l,Qv,To,wo,vo,So,Eo,Io=I(()=>{"use strict";F();ae();kn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===he.FAILED},jl=s=>{let{status:e}=s;return e===he.ABORTED},Yv=s=>{let{status:e}=s;return e===he.PASSED},$l=s=>s.runnerStatus===Kc.SKIPPED,Qv=s=>s.testStatus===Ze.EVALUATING,To=(s,e)=>Object.values(s).filter(t=>{var r,n;return $l(t)&&(et(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,wo=s=>Object.values(s).filter(e=>kn(e)&&Qv(e)).length,vo=s=>Object.values(s).filter(kn),So=s=>Object.values(s).filter(Yv),Eo=s=>Object.values(s).filter(jl)});function eS(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Wl,Ro,Zv,xo,ng=I(()=>{"use strict";Wl=R(require("lodash"));W();Io();Ro=A("debug-reporter"),Zv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],xo=class{constructor(e){this.options=e}onTestStarted(e,t){Ro.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;Ro.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:c,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Wl.default.omit(this.options,Zv),company:Wl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let c=eS(process.argv);Ro.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,i){let o=So(e).length,a=Object.keys(e).length-o;Ro.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Vl,Ft,On=I(()=>{"use strict";ae();Vl=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===N.DEVICE_FARM}},Ft=new Vl});var Hl={};z(Hl,{Reporter:()=>tS});var lr,_n,kr,Co,ig,Gl,tS,ql=I(()=>{"use strict";lr=R(require("chalk")),_n=R(require("lodash"));F();ae();On();Io();kr={success:lr.default.green,warn:lr.default.yellow,error:lr.default.red},{CLI_MODE:Co}=Jt,ig="device",Gl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${lr.default.underline(Je(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?he.PASSED:he.FAILED,n=`(${e.testId})`,i=kr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Gi(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=Je(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(kr.error("Failed runs are:")),console.log(kr.error(t.join(`
18
+ \r`)))}onTestPlanFinished(e,t,r,n,i){let o=vo(e),a=So(e),c=Eo(e),l=a.length,d=c.length,m=o.length,u="",f="";if(Ft.isTestStatusEnabled){let S=wo(e);u=` FAILED-EVALUATING: ${S}`,m-=S,f=` SKIPPED: ${To(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=kr[m?"error":"success"],w=`PASSED: ${l} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Gi(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${w} (Execution ID: ${n})`:g=`Test plan${h} completed ${w} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=_n.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=_n.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=_n.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=_n.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let c=u=>{u.forEach((f,h)=>{var S;let g=(S=f.testData)!=null&&S.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`,w="";f.testOptimization?w=` [${f.testOptimization.reason}]`:et(f,this.options)&&(w="-quarantine"),console.log(" ",h+1,":",`${f.name}${w}`,y,g)})},l=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Co.APPIUM?ig:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${lr.default.underline(n)} slot from ${lr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Co.APPIUM?ig:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${lr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===Co.APPIUM?"device":"browser";if(n)console.log(kr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(kr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===Co.APPIUM?"Appium":"Selenium";console.log(kr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},tS=Gl});var Jl={};z(Jl,{Reporter:()=>aS});function rS(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function sS(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function nS(s){return`${s.visitedUrlsJson||""}`}async function iS(s,e,t,r,n,i){function o(u){let f=Je(s,t,u.testId,u.resultId,r),h={$:{name:rS(u),classname:n,time:rl(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(kn(u)||jl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=kn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return $l(u)&&et(u,i)&&Ft.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=sS(u),h["visited-urls-json"]=nS(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},S={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(y),failures:d(y),timestamp:c(e)};if(Ft.isTestStatusEnabled){S.skipped=To(y,i);let b=wo(y);S.failures-=b,S["failure-evaluating"]=b}return{$:S,testcase:Object.keys(y).map(b=>o(y[b]))}}function c(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function l(u){return Object.keys(u).length}function d(u){return vo(u).length+Eo(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Kl.Builder().buildObject(m)}catch(u){return oS(u)}}function oS(s){let e=new Kl.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var Kl,og,zl,aS,Xl=I(()=>{"use strict";Kl=R(require("xml2js"));F();og=require("fs");On();Io();zl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await iS(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await og.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};aS=zl});var ag={};z(ag,{Reporter:()=>cS});function gs(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var Yl,Ql,cS,cg=I(()=>{"use strict";W();Yl=A("team-city-reporter");Ql=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return gs(n)}onTestStarted(e,t,r,n){if(r){Yl.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,i,o){if(i){Yl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${gs(t)}' details='${gs(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Yl.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${gs(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${gs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${gs(t)}']`)}},cS=Ql});var lg={};z(lg,{Reporter:()=>lS});var Zl,lS,ug=I(()=>{"use strict";Zl=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},lS=Zl});function Po(s){let{platform:e}=process;e==="win32"?(0,Ao.exec)(`start chrome ${s}`):e==="darwin"?(0,Ao.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,Ao.exec)(`google-chrome ${s}`)}var Ao,eu=I(()=>{"use strict";Ao=require("child_process")});var pg={};z(pg,{Reporter:()=>uS});var tu,uS,dg=I(()=>{"use strict";F();eu();tu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=Je(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Po(t)}},uS=tu});var ru,Z,Ut=I(()=>{"use strict";ng();ru=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new xo(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(ql(),Hl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Xl(),Jl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(cg(),ag)),r.includes("console")&&Promise.resolve().then(()=>(ql(),Hl)),r.includes("junit")&&Promise.resolve().then(()=>(Xl(),Jl)),r.includes("json")&&Promise.resolve().then(()=>(ug(),lg)),r.includes("chrome")&&Promise.resolve().then(()=>(dg(),pg))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,i){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var i;let n=t==null?void 0:t(...r);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||r))}}},Z=new ru});async function su(s,e,t){let r=hs[s];if(!r)return;let{slotId:n}=r;if(delete hs[s],!n){Et.warn("failed to find slot slot id",{companyId:e,workerId:s});return}Et.info("release slot id",{companyId:e,slotId:n});try{await iu(e,t,n)}catch(i){Et.error("failed to release slot",{companyId:e,err:i})}}async function pS(s,e){let t=Object.values(hs).filter(Boolean);if(t.length!==0)try{await au(s,e,t)}catch(r){Et.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}function dS(s,e){mg=global.setInterval(()=>pS(s,e),1e4)}async function mS(s,e){let t=Object.keys(hs);if(t.length){Et.warn("not all slots released before end runner flow",{companyId:s});try{await oe(t,r=>su(Number(r),s,e))}catch(r){Et.error("failed to release all slots",{err:r,companyId:s})}}}async function fS(s,e){await mS(s,e),clearInterval(mg)}async function gg(s,e,t){let r;try{r=await nu(s,e)}catch(n){throw Et.error("failed to get slot",{companyId:s,err:n}),new Error(wt.UNKNOWN)}if(Et.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw Et.error("invalid response - get slot",{res:r}),new Error(wt.UNKNOWN);if(r.status==="success")return fg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new at(wt.NOT_FOUND):r.code==="no-available-slot"?new sr("Failed to run test - concurrency limit reached"):(Et.error("invalid code error response - get slot",{res:r}),new at(wt.UNKNOWN))}async function hg(s,e,t,r){let n=hs[r];if(!n)throw new Error("slot not found");Object.assign(n,t),fg(r,n),await ou(s,e,n),Et.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var Et,hs,mg,fg,Ln,ys=I(()=>{"use strict";ye();W();F();ae();Q();Et=A("slot-service"),hs={},mg=null,fg=(s,e)=>{hs[s]=e};Ln={start:dS,end:fS}});function bg(s,e=process){async function t(r){await le(oe(yg,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Nn.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(Nn.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Nn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Nn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Nn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function bs(s){yg.push(s)}var Nn,yg,Mn=I(()=>{"use strict";W();F();Nn=A("process-handler"),yg=[]});var Sg={};z(Sg,{installAllLazyDependencies:()=>bS,lazyRequire:()=>Fe});async function Fe(s,e={}){let t=dl(s);if(t)return t;let r;e.silent||(r=(0,Tg.default)(`Installing ${s} before first usage...`).start());try{let n=await yS(s);return r&&r.succeed(),n}catch(n){hS.warn("failed to install dependency lazily",{dependency:s,err:n});let i=vg(s),o=`${s}@${i}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${o}`;throw r&&r.fail(l),n}}async function yS(s){return Ts.has(s)||(Ts.set(s,wg(s)),Ts.get(s).catch(()=>{Ts.delete(s)})),Ts.get(s)}async function wg(s){let e=dl(s);if(e)return e;let t=vg(s),r=`${s}@${t}`;return await no(Tt(),r),ar(s)}async function bS(){let s=Object.keys(Ic);for(let e of s)await wg(e)}function vg(s){let e=Object.entries(Ic).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Tg,hS,Ts,ws=I(()=>{"use strict";Tg=R(require("ora"));us();W();F();Pi();fn();hS=A("lazy-require"),Ts=new Map});var Eg,ko,Ig=I(()=>{"use strict";Eg=require("istanbul-lib-report"),ko=class extends Eg.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var Rg,xg,Cg,Fn,It,Ag,Oo,cu,Pg,TS,kg,Og,wS,vS,_g,SS,ES,IS,RS,xS,Lg,Dg=I(()=>{"use strict";Rg=R(require("ora")),xg=R(require("dayjs")),Cg=R(require("test-exclude")),Fn=R(require("fs")),It=R(require("path")),Ag=R(require("istanbul-reports")),Oo=R(require("istanbul-lib-report"));ye();Q();F();W();ws();Ig();cu=A("test-run-status"),Pg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},TS=s=>!!Pg(s).search,kg=s=>s?Pg(s).pathname.substring(1):"",Og=(s,e)=>{let t=kg(e);return!new Cg.default({relativePath:!1,include:s}).shouldInstrument(t)},wS=s=>s.substring(0,s.indexOf("?")),vS=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Fe("convert-source-map");if(t==="file"&&!e)throw new x("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},_g=(s,e)=>`${It.resolve(s,kg(e))}.js`,SS=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await oe(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await oe(i.sources,async(o,a)=>{if(Og(r,o))return;let c=_g(e,o);await Fn.promises.mkdir(It.parse(c).dir,{recursive:!0}),await Fn.promises.writeFile(c,i.sourcesContent[a])})})},ES={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(TS(e)&&(e=wS(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=It.dirname(this.getPath(s));return It.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},IS=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=Oo.createContext({dir:t,coverageMap:e,watermarks:Oo.getDefaultWatermarks(),sourceFinder:a=>{try{let c=_g(r,a);return Fn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ko({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:ES}),Ag.create(a,c).execute(o)}),i},RS=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await Fe("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Og(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},xS=async(s,e)=>{let{mergeProcessCovs:r}=await Fe("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await uu(s,"testResult",`runId=${e}`)).data.docs;return await oe(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Un(c,9e4);await oe(l,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await lu(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},Lg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;cu.info("start js coverage process");let n=(0,Rg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=It.resolve(s.codeCoverageReportPath||"./coverage"),o=It.resolve(i,`.js/${(0,xg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?It.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([Fe("istanbul-lib-coverage"),xS(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}cu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),u={};await oe(l.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:w}=d.get(h),S=await vS({sourceMapType:w,source:y,sourceMapDir:a});u[h]=S;let b=await RS(s,{source:y,sourceMap:S,functions:g});m.merge(b)}),await SS(s,o,u);let f=await IS(s,m,i,o);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof x?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),cu.error(l,{err:c})}}});var Ng={};z(Ng,{SELENIUM_PERF_MARKS:()=>Oe,SeleniumPerfStats:()=>Or});var Oe,CS,Or,vs=I(()=>{"use strict";F();Oe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},CS=["ALL",...Object.values(Oe)],Or=class{constructor(){this.marks=Object.fromEntries(CS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=ne();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,Ki(r,50)],[`${t}_P95`,Ki(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Bg={};z(Bg,{initServer:()=>kS,mapFilesToLocalDrive:()=>du});function du(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,_o[t.id]?{screenshot:_o[t.id]}:{})),Object.keys(Lo).forEach(t=>{s.assets||={},s.assets[Ug[t]]=Lo[t]}),s.assets||={},s.assets.screenshots=Object.values(_o)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function kS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Fe("multer"),n=typeof t=="string"?t:AS;await pu.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(c,l,d){let m=JSON.parse(c.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=Bn.join(n,m.testResultId);try{await pu.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(c,l,d){let{fileName:m}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=Bn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,Fg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(_o[d.stepId]=c.file.path),d.testResultId&&PS.includes(d.subType)&&(Lo[d.subType]||=[],Lo[d.subType].push(c.file.path)),l.sendStatus(200)}),o.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>c(d.address()));function m(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new x(`Port ${s} is already in use`));default:return l(u)}}})}var pu,Mg,Bn,Fg,AS,_o,Lo,Ug,PS,mu=I(()=>{"use strict";pu=R(require("fs")),Mg=R(require("os")),Bn=R(require("path")),Fg=R(require("express"));Q();ws();AS=Bn.join(Mg.tmpdir(),"testim/rca/"),_o={},Lo={},Ug={"test-log":"consoleLogs","har-file":"networkLogs"},PS=Object.keys(Ug)});var ur,fu,jn,jg=I(()=>{"use strict";ur=R(require("lodash"));F();W();fu=A("override-test-data-builder"),jn=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return ur.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(e=!1){let{params:t,projectId:r}=this;return this.isObjectNotArray(t)&&t.overrideTestData!==void 0&&(this.isObjectNotArray(t.overrideTestData)&&!ur.isEmpty(t.overrideTestData)?(Object.keys(t.overrideTestData).forEach(n=>this.overrideSingleTest(n,t.overrideTestData[n])),delete t.overrideTestData):fu.error("invalid overrideTestData",{overrideTestData:t.overrideTestData,projectId:r})),this.isObjectNotArray(t)&&t.overrideAllTestsData!==void 0&&(ur.isObject(t.overrideAllTestsData)&&!ur.isEmpty(t.overrideAllTestsData)?(this.testInfoList.map(i=>i.name).forEach(i=>this.overrideSingleTest(i,t.overrideAllTestsData)),delete t.overrideAllTestsData):fu.error("invalid overrideAllTestsData",{overrideAllTestsData:t.overrideAllTestsData,projectId:r})),this.isArrayOfObjects(t)&&e&&this.testInfoList.map(i=>i.name).forEach(i=>this.overrideSingleTest(i,t)),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}fu.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return ur.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),c=r[o],l=this.createNewTestItems(c,t);return r.splice(o,a-o+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=ne();return{...e,resultId:i,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function $n(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw tt.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var pr,tt,OS,_S,LS,DS,Do,$g=I(()=>{"use strict";pr=R(require("lodash"));F();ae();ds();ys();ye();Q();W();Ut();Mn();Dg();vs();mu();ue();me();jg();On();tt=A("test-run-status"),OS=Ir(),_S=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,LS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,DS=ot();Do=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.userTestDataParams={};this.seleniumPerfStats=new Or;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData,this.userTestDataString=this.options.testDataString;let i=an(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:_i||t.parallel||1,browser:i,gitBranch:OS,gitCommit:_S,gitRepoUrl:LS,runnerVersion:DS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:w,allLabels:S}=a,b={originalTestResultId:t,previousTestResultId:r,config:pr.cloneDeep(c),testId:l,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:w,allLabels:S},yu({projectId:n,runId:i,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,Z.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var l;let{project:n,remoteRunId:i,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Mo(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){tt.error("failed to upload test data artifact (runner)",{err:d})}let c=pr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,_r(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){var i;if(et(e,this.options))return;let n=this.exportsGlobal;try{let o=await $n(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token),a=Array.isArray(this.userTestDataParams)?{}:this.userTestDataParams||{},c=(i=e.config)!=null&&i.testDataPrioritized?e.config.testData:{};return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...a,...c,...this.beforeSuiteParams,...o},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw tt.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},tt.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Ze.EVALUATING&&Ft.isTestStatusEnabled){Z.onTestIgnored(e,r,`test in ${Ze.EVALUATING} status`);return}if(l){Z.onTestPassed(i);return}Z.onTestFailed(r,r.failureReason,Je(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,n,c)}calcResultText(e){return e.success?he.PASSED:he.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Z.onTestIgnored(e,r,`test in ${Ze.QUARANTINE}`)}monitorMemoryUsage(e){let t=sl();t.isOverThreshold&&tt.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&du(o,tt),o.resultUrl=Je(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Z.onTestFinished(o,e,i);let c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await $n(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){tt.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await _r(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw tt.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=Yc;return e&&(n=i),es(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g,y;let c=e.browser?un(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=ts(O,n)&&ln(a.nativeApp)&&!e.appId,d=ir(e)&&(es(a.nativeApp,n)||l),m=et(a,e)||d,u={testId:a.testId,testOptimization:a.testOptimization,status:m?he.SKIPPED:he.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ze.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,testDataPrioritized:((h=a.testData)==null?void 0:h.prioritize)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((g=a.testData)==null?void 0:g.total)||null,testDataIndex:((y=a.testData)==null?void 0:y.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:c.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await Ln.end(r,t),e==="mongo"&&await xn.end(t)}async executionStart(e,t,r,n,i){tt.info("execution started",{executionId:e,gridId:this.execConfig.gridId,gridHost:this.execConfig.gridHost,gridName:this.execConfig.gridName,gridType:this.execConfig.gridType,parallel:this.execConfig.parallel,runnerVersion:this.execConfig.runnerVersion,source:this.execConfig.source});let{options:o}=this,{remoteRunId:a,projectData:c,company:{companyId:l}={},slotService:d}=o;bs(()=>Promise.all([this.endKeepAlive(d,t,l),No("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...O.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=this.userTestDataString,f=await $n(new Function(u||""));if(f&&(this.userTestDataParams=f,Array.isArray(f))){let T=new jn(f,pr.cloneDeep(this.testInfoList),t);this.testInfoList=T.overrideTestData(!0)}let h=await $n(o.beforeSuite,m),g=new jn(h,pr.cloneDeep(this.testInfoList),t);this.testInfoList=g.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=h;let{testInfoList:y}=this,w=[],S=[],b=[];for(let T of y){if(T.isBeforeTestPlan){w.push(T);continue}if(T.isAfterTestPlan){b.push(T);continue}S.push(T)}let v=async()=>{let T=pr.cloneDeep(this.testRunStatus);await oe(Object.keys(T),async B=>{var j;let G=T[B],E=(j=G.config)==null?void 0:j.testData,k=G.testId,D=await Mo(t,k,B,E,c.defaults);D&&(delete G.config.testData,G.config.testDataUrl=D)});let C=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),_=hu({executionId:e,projectId:t,labels:n||[],startTime:r,executions:T,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:C,intersections:o.intersections});return this.executionStartedPromise=_,_.catch(B=>tt.error(B)),_};try{await v()}catch(T){tt.error("Failed to start suite",{err:T}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:w,tests:S,afterTests:b}}concatSeleniumPerfMarks(e){pr.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=cl(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===he.PASSED&&n++,m===he.SKIPPED&&i++,m===he.FAILED&&u===Ze.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await $n(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),tt.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Lg(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await No("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw tt.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await gu(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function bu(s){var i;let e=s.canary?"-master.zip":".zip",t=`${tr}/testim-headless${e}`,r=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(i=s.company)==null?void 0:i.companyId,projectId:s.project,runnerEnvironment:Js});return r||(NS.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),r=`${tr}/testim-headless.zip`),!(s.ext||s.extensionPath)&&r&&(t=r,s.testimHeadlessExtensionDownloadUrl=r),{chrome:t,"edge-chromium":t}}function Wg(s){let{chrome:e}=bu(s);return e}function Fo(s){let e=`${tr}/sessionPlayer`;return s.canary?`${e}-master`:e}var NS,Wn=I(()=>{"use strict";ue();me();W();NS=A("runOptionsUtils")});function Ss(s){var n;let t=(n=new RegExp(`^\\b(${Object.values(Tu).join("|")})`).exec(s))==null?void 0:n[0];return t||Tu[Gd]||"usw2"}var Tu,Gg,Uo=I(()=>{"use strict";ue();Tu={"us-west-2":"usw2","eu-central-1":"euc1"},Gg=Object.fromEntries(Object.entries(Tu).map(([s,e])=>[e,s]))});function Hg(s,e){if(e){if(!$S.has(e)){Vn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var qg,zg,Yt,Kg,Jg,Xg,Bo,Yg,Vn,MS,FS,Gn,US,BS,jS,ce,$S,jo=I(()=>{"use strict";qg=R(require("ms")),zg=R(require("p-retry")),Yt=R(require("node:os")),Kg=R(require("portfinder")),Jg=R(require("node:child_process"));F();Ge();ye();Xg=R(require("node:fs")),Bo=R(require("node:fs/promises")),Yg=require("node:path");Q();W();Wn();ae();me();F();Uo();Vn=A("lambdatestService"),MS="https://downloads.lambdatest.com/tunnel/v3",FS={win32ia32:"windows/32bit/LT_Windows.zip",win32x64:"windows/64bit/LT_Windows.zip",darwinia32:"mac/32bit/LT_Mac.zip",darwinx64:"mac/64bit/LT_Mac.zip",darwinarm64:"mac/64bit/LT_Mac.zip",linuxia32:"linux/32bit/LT_Linux.zip",linuxx64:"linux/64bit/LT_Linux.zip",freebsdia32:"freebsd/32bit/LT_Freebsd.zip",freebsdx64:"freebsd/64bit/LT_Freebsd.zip"},Gn=`${Yt.tmpdir()}/LT`,US=`${Gn}/LT`,BS=(0,qg.default)("15m"),jS="2560x1440",ce=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===N.TESTIM_LAMBDATEST||e.type===N.LAMBDATEST||e.type===N.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t,r){ce.isLambdatestGrid(e)&&(ce.lambdatestConfigPromise||=wu(t,r),ce.lambdatestConfig=await ce.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?BS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await Te(US))return;let t=FS[Yt.platform()+Yt.arch()];if(!t)throw new Error(`tunnel on ${Yt.platform()+Yt.arch()} platform is not supported.`);let r=`${Gn}.zip`;await Ye(`${MS}/${t}`,r),await Qe(r,Gn)}static async chmodLtTunnel(e){if(!(Yt.platform()==="win32"||!await Te(e))){try{await Bo.access(e,Xg.constants.X_OK);return}catch{}try{await Bo.chmod(e,"777")}catch(r){throw Vn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ie(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ce.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Kg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;ce.tunnelName=ne();let l=["--tunnelName",ce.tunnelName,"--infoAPIPort",String(t)];if(O.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],o&&a)l=[...l,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(O.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(l=[...l,...tl(u)])}if(O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)l=[...l,"--user",n,"--key",i];else throw new x("tunnel requires username and password");if(c)try{let u=new URL(c);l=[...l,"--proxy-host",u.hostname],u.port&&(l=[...l,"--proxy-port",u.port]),u.username&&u.password&&(l=[...l,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new x("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await ce.delay(3e3),await ce.chmodLtTunnel((0,Yg.join)(Gn,"LT")),ce.tunnel=Jg.spawn("./LT",l,{cwd:Gn});let d="",m="";ce.tunnel.stdout.on("data",u=>{d+=u.toString()}),ce.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,zg.default)(()=>ve(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Vn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),Vn.error("Failed to start LT tunnel",{err:u}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ce.tunnel))return new Promise((t,r)=>{ce.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ce.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,c){var C;if(!this.isActive)return{};let l=ce.lambdatestConfig.CAPABILITIES[t]||{},d={...ce.tunnelName&&{tunnel:!0,tunnelName:ce.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:Hg(n,a==null?void 0:a.os)||Hg(n,(C=o==null?void 0:o.lt)==null?void 0:C.platform)||l.platform||ce.lambdatestConfig.PLATFORM,resolution:ce.lambdatestConfig.RESOLUTION??jS,...t!=="safari"&&{version:l.version}};if(c!==J.APPIUM&&c!==J.SELENIUM&&!f){let _=bu({canary:u});!h&&_[t]&&(m=[...m,_[t]]),h&&Me(h)&&(m=[...m,h]),m.length||Vn.warn("No extension was loaded in LambdaTestService",{extUrls:_,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&Me(g)&&(m=[...m,g]);let w=Ss(e.project||""),b={euc1:"eu"}[w],v=b?{region:b}:{};return{"LT:Options":{build:r,name:`${n} - ${i}`,...v,selenium_version:ce.lambdatestConfig.SELENIUM_VERSION,timezone:ce.lambdatestConfig.TIMEZONE,...l,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}},$S=new Set(["Linux","Windows 10","Windows 11","MacOS Tahoe","MacOS Sequoia","macOS Sonoma","macOS Ventura","macOS Monterey","macOS Catalina","macOS Big Sur","macOS Mojave","macOS High Sierra","macOS Sierra","OS X El Capitan","OS X Yosemite","OS X Mountain Lion"])});var Qg,WS,$o,vu=I(()=>{"use strict";Q();Qg=["platformName","platform","app","bundleId","appPackage","extensions"],WS=["selenium_version","protocol","host","port","path","build"],$o=(s,e)=>{let t=e==="lambdaTest"?[...Qg,...WS]:Qg,r=[],n=[s];for(;n.length;){let i=n.pop();for(let[o,a]of Object.entries(i))t.includes(o)&&r.push(o),a&&typeof a=="object"&&n.push(a)}if(r.length)throw new x(`Custom capabilities contains forbidden keys: ${r.join(", ")}`)}});function GS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function lh(s){return nh.readFileSync(s,{encoding:"base64"})}function uh(s,e,t,r){if(t!=null&&t.isLambdatestRun()&&Me(s))return null;if(s){if(r)return s.endsWith(".zip")?(Qe(s,th),th):s;let n=lh(s);Is.info(`adding extension: custom, path: ${s} length: ${n.length} hash: ${Iu(n)} current extension count: ${e.length}`),e.push(n)}return null}function ph(s,e,t,r,n,i){if(n!=null&&n.isLambdatestRun())return null;let o=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!o){let m=typeof s.ext=="string"?s.ext:`${__dirname}/..`,u=r||m,f=`--load-extension=${u}`;return Is.info(`adding extension: testim unpacked , path: ${u}`),t.push(f),null}let c=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&o&&(c=Lr.basename(o));let l=Lr.join(process.cwd(),c);if(i)return Qe(l,eh),eh;let d=lh(l);return Is.info(`adding extension: testim zipped, path: ${l} length: ${d.length} hash: ${Iu(d)} current extension count: ${e.length}`),e.push(d),null}function HS(s,e,t,r,n,i,o,a){var g,y;let c=t.seleniumName||t.browserValue,l=[],d=[...ah];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Su.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Su.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1,"profile.password_manager_leak_detection":!1},w3c:!0};if(Eu(n)){let w=O.flags.DFAcceptInsecureOrigins.getValue();typeof w=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${w}`),m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}Eu(n)&&c==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(w=>d.push(`--${w}`));try{let w=Wo();w.length&&w.forEach(S=>d.push(`--disable-features=${S}`))}catch{}e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Su.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:c});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Jc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),uh(r,l,o),a===J.EXTENSION&&ph(e,l,d,i,o),l.length>0&&(m.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[c],h={MicrosoftEdge:"ms",chrome:"goog"}[c];return ce.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function zS(s,e,t){let r={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":rh.join(","),"browser.helperApps.neverAsk.openFile":rh.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{"LT:Options":{enableCustomTranslation:!0}}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function Es(s){return`${s.width}x${s.height}`}function ZS(s){let{platform:e}=s;if(!e)return Es(sh);let t=e.split(" ")[1];return e.startsWith("Windows")&&QS.has(t)?Es(JS):e==="Linux"?Es(KS):e.startsWith("macOS")?Es(XS):Es(e==="OS X El Capitan"||e==="OS X Yosemite"?YS:sh)}function eE(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(n["sauce:options"].screenResolution=ZS(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let i=(0,oh.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,rt.merge(i,n,r)}return rt.merge(n,r)}return{}}function tE(s){let{runnerOptions:e}=s;if(rt.isEmpty(e.browserstack))return{};let{projectData:t,testRunConfig:r,testId:n,testName:i,executionId:o,executionName:a}=s,c={buildName:`${a} - ${o}`,sessionName:`${i} - ${n}`,projectName:`${t.name} - ${t.projectId}`,...e.browserstack};return r&&r.browserValue==="safari"&&r.bs.safari_version&&(c.os_version=r.bs.safari_version,r.bs.safari_version==="10"&&Object.assign(c,{"safari.options":{technologyPreview:!0}})),c}function rE(s){return s.perfecto?s.perfecto:{}}function sE(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function nE(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,i=r||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=vc(i,o)),a}function Wo(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function Vo(s){var B,G,E,k;let{overrideConfiguration:e,browserOptions:t,testId:r,testName:n,testRunConfig:i,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:d,testResultId:m,lambdatestService:u,mode:f,customCapabilities:h,useLocalChromeDriver:g}=s;if(o.mode==="local"){let D=[],j=[...ah],V={};t.headless&&j.push("--headless"),t.silentDebuggerExtensionApi&&j.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&j.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let re=Wo();re.length&&re.forEach(ge=>j.push(`--disable-features=${ge}`))}catch{}t.chromeExtraArgs&&t.chromeExtraArgs.forEach(re=>j.push(`--${re}`)),t.chromeBinaryLocation&&(V.binary=t.chromeBinaryLocation);let K,q=null;return f!==J.SELENIUM&&(K=ph(t,D,j,null,u,g)),q=uh(a,D,u,g),g&&j.push("--enable-unsafe-extension-debugging","--remote-debugging-pipe"),{logLevel:Zg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:j,extensions:D,...V},browserName:"chrome",...g&&{webSocketUrl:!0}},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515,...g&&K&&{unzippedTestimExtensionPath:K},...g&&q&&{unzippedCustomExtensionPath:q}}}let{driverRequestTimeout:y,driverRequestRetries:w}=t,S=nE(t,o),b={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Zg,connectionRetryTimeout:y,connectionRetryCount:w,getSessionTimeout:Math.max(u.getSessionTimeout,t.getSessionTimeout),getSessionRetries:u.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0},...!rt.isEmpty(S)&&{headers:S},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Eu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,b.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(b.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let v=Number(t.browserTimeout/1e3),T=t.browser||(i==null?void 0:i.browserValue),C={runnerOptions:t,testId:r,testName:n,testRunConfig:i,executionId:c,executionName:l,projectData:d};rt.merge(b.desiredCapabilities,eE(t,n,i),tE(C),rE(t),sE(t,T,v),u==null?void 0:u.getCapabilities(t,T,c,m,n,i,e,f));let _=null;switch(!t.ext&&!t.extensionPath&&((B=o.host)!=null&&B.endsWith(".testim.io"))&&!t.canary&&f===J.EXTENSION&&(T==="chrome"||T==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(_="/opt/testim-headless"),T){case"chrome":case"edge-chromium":b=qS(b,t,i,a,o,_,u,f);break;case"firefox":b=zS(b,t,u);break;case"safari":case"safari technology preview":b=GS(b,T);break;default:break}h?($o(h,o.type),rt.merge(b.desiredCapabilities,h)):rt.merge(b.desiredCapabilities,t.seleniumCapsFileContent);try{let D={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},j=re=>re[o.provider]||re[b.host]||re[D[b.host]],V=re=>{var ge,ze;return j(re)||re[(ge=b.desiredCapabilities)==null?void 0:ge.browserName]||re[(ze=b.desiredCapabilities)==null?void 0:ze.version]||re||{}},K=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),q=V(V(K));Object.keys(q).length&&(Is.info(`Adding custom capabilities: ${JSON.stringify(q)}`),Object.assign(b.desiredCapabilities,q))}catch(D){Is.error("Failed to load custom capabilities",{error:D,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(b.desiredCapabilities&&!b.capabilities&&(VS(b),b.capabilities={alwaysMatch:b.desiredCapabilities,firstMatch:[{}]},delete b.desiredCapabilities),b.hostname=b.host,s.printFinalCaps){let D=(G=b.capabilities)==null?void 0:G.alwaysMatch,j=JSON.parse(JSON.stringify(b)),V=(E=j==null?void 0:j.capabilities)==null?void 0:E.alwaysMatch,K=re=>re.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(re=>{var ge,ze;V!=null&&V[re]&&(V[re].extensions=(ze=(ge=D==null?void 0:D[re])==null?void 0:ge.extensions)==null?void 0:ze.map(K))}),V!=null&&V.loadExtension&&(V.loadExtension=(k=D==null?void 0:D.loadExtension)==null?void 0:k.map(K));let q=require("node:util");console.log(q.inspect(j,{showHidden:!1,depth:null,colors:!0}))}return b}var nh,Lr,ih,rt,oh,Is,Zg,Su,ah,ch,eh,th,Iu,Eu,VS,qS,rh,sh,KS,JS,XS,YS,QS,Go=I(()=>{"use strict";nh=R(require("node:fs")),Lr=R(require("node:path")),ih=R(require("node:crypto")),rt=R(require("lodash"));F();ue();W();zc();F();me();ae();jo();vu();oh=require("lodash"),Is=A("testim-desired-capabilities-builder"),Zg=Oi?"debug":"silent",Su={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},ah=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],ch=Lr.join(vt,"extensions"),eh=Lr.join(ch,"testim-headless"),th=Lr.join(ch,"custom-extension"),Iu=(...s)=>ih.createHash("sha256").update(s.join("")).digest("hex"),Eu=s=>s.type===N.DEVICE_FARM||s.type===N.HYBRID&&s.provider==="devicefarm",VS=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=O.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{Is.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};qS=rt.memoize(HS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(rt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return Iu(o,a,c,r,l,i)}),rh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];sh={width:1920,height:1080},KS={width:1920,height:1200},JS={width:2560,height:1600},XS={width:2360,height:1770},YS={width:2048,height:1536},QS=new Set(["7","8","8.1","10","11"])});function Bt(s){var e,t,r,n,i,o,a,c;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||((t=s.message)==null?void 0:t.toLowerCase())==="unknown error"||((r=s.message)==null?void 0:r.match(/Unknown timeout type/))||s.name==="unknown command"||((n=s.message)==null?void 0:n.match(/did not match a known command/))||((i=s.message)==null?void 0:i.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=s.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((c=s.message)==null?void 0:c.match(/\.\w* is not a function/))}function mh(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var Ru=I(()=>{"use strict"});function xu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function i(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return i(y,f)}function o(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=i(u,"stroke-width");return!!g&&parseInt(g,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(u){return i(u,"overflow")==="hidden"}function c(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:c(f))}function l(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:l(u.parentNode):!1}if(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return xu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||c(s))}var fh=I(()=>{"use strict"});var gh,hh,jt,iE,oE,Ho,yh=I(()=>{"use strict";gh=R(require("promise-queue")),hh=R(require("webdriverio"));ue();$e();F();W();qr();fh();Ru();vs();jt=A("WebDriverApi"),iE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},oE={implicit:0,pageLoad:1,script:2},Ho=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}rejectWithLog(e,t){let{testName:r,testResultId:n}=this,i=t?t.toString().slice(0,2e3):"";throw jt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Rc!==void 0&&(e=Rc);let t=1/0;this.queue=new gh.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async installExtensions(e){var r;let t=[e==null?void 0:e.unzippedTestimExtensionPath,e==null?void 0:e.unzippedCustomExtensionPath].filter(Boolean);for(let n of t)await((r=this.client)==null?void 0:r.send({method:"webExtension.install",params:{extensionData:{type:"path",path:n}}}))}async initClient(e,t,r,n,i){var c,l,d,m,u,f,h,g;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let o=((c=e.capabilities.alwaysMatch)==null?void 0:c.loadExtension)||((l=e.capabilities.alwaysMatch)==null?void 0:l.loadExt)||((f=(u=(m=(d=e.capabilities.alwaysMatch)==null?void 0:d["goog:chromeOptions"])==null?void 0:m.extensions)==null?void 0:u[0])==null?void 0:f.slice(0,80)),a=(h=this.seleniumPerfStats)==null?void 0:h.markStart(Oe.GET_BROWSER);try{await this.addToQueue(async()=>{jt.info("requesting browser",{testResultId:r,testName:t,extUrl:o}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await hh.remote(e),this.client.on("dialog",async y=>{try{await y.accept()}catch{}}),n&&await this.installExtensions(i),this.logGridStatus(r)}),M("after client init")}finally{(g=this.seleniumPerfStats)==null||g.markEnd(a,Oe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){jt.info("grid status is not supported by the grid",{testResultId:e});return}jt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),jt.info("grid status",{gridStatusMsg:i.message,ready:i.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){jt.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await o()}catch(a){if(Bt(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.execute(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Bt(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Oe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,Oe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Oe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Be(e)))}finally{this.seleniumPerfStats.markEnd(t,Oe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(async()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(xu,{ELEMENT:e,[er]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Bt(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(mh(e,this.isSafari(),jt))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let i=[];return i[oE[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(Bt(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Be(e)),await this.elementIdValue(Be(e),t)}async getViewportSize(e){let t=await this.execute(iE);if(typeof e=="string"&&/(width|height)/.test(e)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitFormManually(e){return this.addToQueue(async()=>{var i;let t=(i=this.client)==null?void 0:i.$(e),r=t.$('button[type="submit"]');return await r.isExisting()?r.click():t.$("input:last-of-type").keys("Enter")})}async findElementAndPress(e,t,r){let n;try{n=await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}catch(i){if(i.message.includes("unexpected alert open")||i.message.includes("dialog detected"))await this.alertAccept().catch(o=>jt.warn("failed to click on alert",{err:o})),n=await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})});else throw i}return{value:n}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let i=this.client.$(e);await this.client.action("pointer").move({origin:i}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let n=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(n,i)}try{return await r()}catch(n){throw n}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayed()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){jt.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return jt.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var dr={};z(dr,{getSessionPlayer:()=>ee,options:()=>Au});var qo,Au,Cu,ee,Se=I(()=>{"use strict";qo=require("path");W();Au={playerPath:void 0},ee=()=>{if(Cu)return Cu;let s=($e(),Ke(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(bn(),Ke(yn)),t=e(),r=Au.playerPath?(0,qo.resolve)(Au.playerPath,"src/background/sessionPlayerInit.ts"):(0,qo.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),Cu=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(fm),n}});var bh={};z(bh,{doubleClick:()=>aE});var aE,Th=I(()=>{"use strict";aE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function f(S,b,v){return v>S&&v<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,w=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:w}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},l=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?c(h,f.x,f.y):l(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Hn={};z(Hn,{dispatchFocus:()=>cE});function cE(s,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function r(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let i=getLocatedElement(s);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var qn=I(()=>{"use strict"});var Ih={};z(Ih,{WebDriver:()=>Nr});async function dE(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await uE(r):void 0}catch(r){He.info("Error getting cdpAddress",r);return}}var xs,Sh,Eh,He,Rs,lE,wh,uE,Dr,pE,vh,zn,Nr,Kn=I(()=>{"use strict";xs=R(require("lodash"));F();$e();Go();Sh=R(require("p-retry")),Eh=R(require("ua-parser-js"));qr();W();Ru();yh();Q();me();vs();He=A("webdriver"),[Rs,lE]=[0,2],{extractElementId:wh,getCdpAddressForHost:uE}=X,Dr=()=>(Se(),Ke(dr)).getSessionPlayer().codeSnippets,pE=()=>(Se(),Ke(dr)).getSessionPlayer().locatorBuilderUtils,vh=()=>(Se(),Ke(dr)).getSessionPlayer().utils,zn=()=>(Se(),Ke(dr)).getSessionPlayer().positionUtils;Nr=class extends Ho{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.keepAliveFailedCallbacks=[];this.generalKeepAliveFailures=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null)}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}registerToKeepAliveFailed(t){this.keepAliveFailedCallbacks.push(t)}unregisterToKeepAliveFailed(t){this.keepAliveFailedCallbacks=this.keepAliveFailedCallbacks.filter(r=>r!==t)}async init(t){var B,G,E,k,D,j,V,K;let{projectData:r,overrideConfiguration:n,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:u,testResultId:f,seleniumPerfStats:h,fastInit:g,lambdatestService:y,printFinalCaps:w,mode:S,customCapabilities:b,useLocalChromeDriver:v}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((E=(G=(B=i==null?void 0:i.company)==null?void 0:B.activePlan)==null?void 0:G.premiumFeatures)==null?void 0:E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let T=Vo({projectData:r,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:u,testResultId:f,lambdatestService:y,overrideConfiguration:n,printFinalCaps:w,mode:S,customCapabilities:b,useLocalChromeDriver:v});T.desiredCapabilities&&delete T.desiredCapabilities.marionette,T.capabilities&&delete T.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(y==null?void 0:y.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=h;let C=g?0:1500,_=g?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let q={unzippedTestimExtensionPath:T.unzippedTestimExtensionPath,unzippedCustomExtensionPath:T.unzippedCustomExtensionPath},re=await this.initClient(T,a,f,v,q);M("after initResult before getCdpAddress in init"),this.cdpUrl=await dE(re),M("after getCdpAddress in webdriver.js init"),He.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await ie(C),O.flags.dontFocusOnInit.isEnabled()||await _(),M("after focus and delay in webdriver.js init")}catch(q){let re=JSON.stringify(xs.omit(T,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));He.error("failed to init webdriver",{err:q,capabilitiesAsString:re});let ge=((D=(k=i==null?void 0:i.company)==null?void 0:k.activePlan)==null?void 0:D.plan)==="free";throw(j=q.stack)!=null&&j.includes("at startWebDriverSession")&&((V=q.message)!=null&&V.startsWith("Failed to create session"))&&((K=q.message)!=null&&K.includes("Timeout awaiting 'request'"))&&ge?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(q.message)?new Kr(q.message):/capabilit(y|ies)/.test(q.message)?new Mi(q.message):/403 Forbidden/.test(q.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(q.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${q.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>xs.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=ne();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,He.warn("close unexpected alert open"),await this.alertAccept().catch(c=>He.warn("failed to click on alert",{err:c}));return}if(He.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;He.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.handleThresholdBasedError(this.browserClosedCallbacks,a)}else this.generalKeepAliveFailures++,this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures>=3&&this.handleThresholdBasedError(this.keepAliveFailedCallbacks,a)}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}handleThresholdBasedError(t,r){t.forEach(n=>{try{n(r)}catch{}})}async switchToLocatedFrame(t){let r=await this.getElement(t);if(!r.value)throw new Error("Element not found");let n=wh(r.value);return await this.switchToFrame({ELEMENT:n,[er]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new Fi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(Oe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Oe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
19
+ var fn = ${Dr().getLocatedElementCode};
20
20
  return fn.apply(null, arguments);
21
21
  `,t)}finally{this.seleniumPerfStats.markEnd(r,Oe.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,Oe.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...n){return await this.timeouts("script",r),await this.executeAsync(t,...n)}async markDynamicParent(t,r){function n({attributeName:i,attributeValue:o,locatedElement:a}){let c=getLocatedElement(a);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(i,o)}await this.executeJS(`
22
- var getLocatedElement = ${Nr().getLocatedElementCode};
22
+ var getLocatedElement = ${Dr().getLocatedElementCode};
23
23
  var setDynamicParentAttribute = ${n.toString()};
24
24
  return setDynamicParentAttribute.apply(null, arguments)
25
25
  `,{attributeName:pE().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(n){let i=getLocatedElement(n);if(!i)return null;let o=parseInt(window.getComputedStyle(i).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(i).paddingLeft.replace("px",""),10)||0,c=i.getBoundingClientRect();return{top:Math.round(c.top+o),left:Math.round(c.left+a)}}return this.executeJS(`
26
- const getLocatedElement = ${Nr().getLocatedElementCode};
26
+ const getLocatedElement = ${Dr().getLocatedElementCode};
27
27
  const getLocation = ${r.toString()};
28
28
  return getLocation.apply(null, arguments)
29
29
  `,t)}getElementLocationWithPadding(t){return this.getLocatedElementRectWithPadding(t)}getLocatedElementRect(t){function r(n){let i=getLocatedElement(n);if(!i)return null;let o=i.getBoundingClientRect();return{bottom:Math.round(o.bottom),height:Math.round(o.height),x:Math.round(o.left),right:Math.round(o.right),y:Math.round(o.top),width:Math.round(o.width)}}return this.executeJS(`
30
- const getLocatedElement = ${Nr().getLocatedElementCode};
30
+ const getLocatedElement = ${Dr().getLocatedElementCode};
31
31
  const getLocation = ${r.toString()};
32
32
  return getLocation.apply(null, arguments)
33
33
  `,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function r(i,o){function a(u){var h;return(h=u.childNodes)!=null&&h.length&&[...u.childNodes].filter(g=>g.nodeType===Node.ELEMENT_NODE).forEach(g=>{typeof g.tagName=="string"&&g.tagName.toLowerCase()==="title"?u.removeChild(g):a(g)}),u}function c(u){return["INPUT","TEXTAREA"].includes(u.tagName)}function l(u){var f,h,g;try{if(u.shadowRoot&&!((g=(h=Object.getOwnPropertyDescriptor((f=u.ownerDocument.defaultView)==null?void 0:f.Node.prototype,"textContent"))==null?void 0:h.get)!=null&&g.toString().includes("[native code]")))return u.shadowRoot.textContent.replace(/(\r\n|\n|\r)/gm,"")}catch{}if(o&&Array.prototype.some.call(u.children,y=>y.hidden)){let y=u.cloneNode(!0);return Array.prototype.filter.call(y.children,S=>S.hidden).forEach(S=>y.removeChild(S)),y.textContent.replace(/(\r\n|\n|\r)/gm,"")}return u.textContent.replace(/(\r\n|\n|\r)/gm,"")}function d(u){if(c(u))return u.value;if(u instanceof SVGElement){let f=u.cloneNode(!0);return a(f).textContent.replace(/(\r\n|\n|\r)/gm,"")}return l(u)}let m=getLocatedElement(i);return m?d(m):""}let{value:n}=await this.executeJS(`
34
- const getLocatedElement = ${Nr().getLocatedElementCode};
34
+ const getLocatedElement = ${Dr().getLocatedElementCode};
35
35
  const extractText = ${r.toString()};
36
36
  return extractText.apply(null, arguments)
37
- `,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var i,o;let r=Nr().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(Oe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,Oe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,Oe.GET_HTML);let c=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(o=(i=this.client)==null?void 0:i.requestHandler)!=null&&o.sessionID||Object.assign(c,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),c}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class i extends Error{}function o(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,Sh.default)(async()=>{let{value:l}=await this.windowHandleSize(),{value:d}=await this.execute(o),m=l.width-d.screenWidth,u=l.height-d.screenHeight;await this.windowHandleSize({width:t.width+m,height:t.height+u});let{value:f}=await this.execute(o);if(f.screenWidth!==t.width||f.screenHeight!==t.height)throw new i},{retries:5-1,factor:1,minTimeout:0}).catch(l=>{if(!(l instanceof i))throw l});if(typeof t!="object"||typeof t.width!="number"||typeof t.height!="number"||r!==void 0&&typeof r!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(r===void 0?!0:r)?a():this.windowHandleSize(t)}setViewportSize(t,r){return this.setViewportSizeNEW({width:t,height:r},!0)}getBrowserMajorVersion(t){var r;try{return parseInt(((r=t.browser)==null?void 0:r.version)||"0",10)}catch(n){return $e.error("failed to get browser version",{err:n}),0}}async getBrowserAndOS(){function t(a){let c=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(c[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(c[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";c=c[2]?[c[1],c[2]]:[a.appName,a.appVersion,"-?"];let l=a.match(/version\/(\d+)/i);return l!==null&&c.splice(1,1,l[1]),c[0].toLowerCase()}if(this.browserAndOS)return this.browserAndOS;function r(){var a;return(a=window==null?void 0:window.navigator)!=null&&a.userAgent?window.navigator.userAgent:"unknown"}let{value:n}=await this.executeJS(r),i=(0,Eh.default)(n),o=i.os;return this.browserAndOS={os:`${o.name} ${o.version}`,browserMajor:this.getBrowserMajorVersion(i),browser:t(n),userAgent:n,browserVersion:i.browser.version},this.browserAndOS}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:n,clickOffset:i}=t,o=Mr().calculateElementMiddlePoint(n),a=i.x,c=i.y;return!vh().isWithinBounds(n.left,n.left+n.width,o.x+a)||!vh().isWithinBounds(n.top,n.top+n.height,o.y+c)?($e.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,c,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:n,clickOffset:i}=t,o=n.left+i.x+r.x,a=n.top+i.y+r.y;return{x:o,y:a}}async actWithActionsAPI(t,r,n,i){let o=this.getRelativeMoveActions(t,n),a=this.getClickActions(i,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(a)}])}catch(c){$e.error("tried to use element origin but failed because of visibility, trying absolute",c);let{x:l,y:d}=this.computeAbsoluteMovement(t),m=this.getMoveActions(l,d);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:m.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,mr,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(Th(),bh)),Promise.resolve().then(()=>(zn(),qn))]);return this.executeCodeAsync(`
38
- var getLocatedElement = ${Nr().getLocatedElementCode};
37
+ `,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var i,o;let r=Dr().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(Oe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,Oe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,Oe.GET_HTML);let c=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(o=(i=this.client)==null?void 0:i.requestHandler)!=null&&o.sessionID||Object.assign(c,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),c}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class i extends Error{}function o(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,Sh.default)(async()=>{let{value:l}=await this.windowHandleSize(),{value:d}=await this.execute(o),m=l.width-d.screenWidth,u=l.height-d.screenHeight;await this.windowHandleSize({width:t.width+m,height:t.height+u});let{value:f}=await this.execute(o);if(f.screenWidth!==t.width||f.screenHeight!==t.height)throw new i},{retries:5-1,factor:1,minTimeout:0}).catch(l=>{if(!(l instanceof i))throw l});if(typeof t!="object"||typeof t.width!="number"||typeof t.height!="number"||r!==void 0&&typeof r!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(r===void 0?!0:r)?a():this.windowHandleSize(t)}setViewportSize(t,r){return this.setViewportSizeNEW({width:t,height:r},!0)}getBrowserMajorVersion(t){var r;try{return parseInt(((r=t.browser)==null?void 0:r.version)||"0",10)}catch(n){return He.error("failed to get browser version",{err:n}),0}}async getBrowserAndOS(){function t(a){let c=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(c[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(c[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";c=c[2]?[c[1],c[2]]:[a.appName,a.appVersion,"-?"];let l=a.match(/version\/(\d+)/i);return l!==null&&c.splice(1,1,l[1]),c[0].toLowerCase()}if(this.browserAndOS)return this.browserAndOS;function r(){var a;return(a=window==null?void 0:window.navigator)!=null&&a.userAgent?window.navigator.userAgent:"unknown"}let{value:n}=await this.executeJS(r),i=(0,Eh.default)(n),o=i.os;return this.browserAndOS={os:`${o.name} ${o.version}`,browserMajor:this.getBrowserMajorVersion(i),browser:t(n),userAgent:n,browserVersion:i.browser.version},this.browserAndOS}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:n,clickOffset:i}=t,o=zn().calculateElementMiddlePoint(n),a=i.x,c=i.y;return!vh().isWithinBounds(n.left,n.left+n.width,o.x+a)||!vh().isWithinBounds(n.top,n.top+n.height,o.y+c)?(He.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,c,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:n,clickOffset:i}=t,o=n.left+i.x+r.x,a=n.top+i.y+r.y;return{x:o,y:a}}async actWithActionsAPI(t,r,n,i){let o=this.getRelativeMoveActions(t,n),a=this.getClickActions(i,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(a)}])}catch(c){He.error("tried to use element origin but failed because of visibility, trying absolute",c);let{x:l,y:d}=this.computeAbsoluteMovement(t),m=this.getMoveActions(l,d);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:m.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,Rs,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(Th(),bh)),Promise.resolve().then(()=>(qn(),Hn))]);return this.executeCodeAsync(`
38
+ var getLocatedElement = ${Dr().getLocatedElementCode};
39
39
  var dispatchFocus = ${n.toString()};
40
40
  var doubleClick = ${r.toString()};
41
41
  var eventData = arguments[0];
42
42
  var done = arguments[1];
43
43
  return doubleClick.call(null, eventData, done);
44
- `,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,mr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,lE,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(je(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw n}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(n){if(je(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw n}}async dragAndDropOldAPI(t,r){return await this.moveTo(t),await this.buttonDown(),await this.moveTo(r),await this.buttonUp()}async calculateElementMiddlePoint(t,r={top:0,left:0}){let n=await this.getLocatedElementRect(t);if(!(n!=null&&n.value))throw $e.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:i,y:o,width:a,height:c}=n.value;return{x:r.left+i+a/2,y:r.top+o+c/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:i}=r.clickOffset;try{return await this.moveTo(t,n,i)}catch(o){if(je(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,n="viewport",i=0){return[{type:"pointerMove",duration:i,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){$e.error("tried to use element origin but failed because of visibility, trying location",n);let i=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(i)}}getDragCoordinates(t){let r=t.filter(o=>o.event==="mousemove"||o.event==="pointermove"),n=r[0].pointerPosition,i=r.at(-1).pointerPosition;return{xDiff:i.screenX-n.screenX,yDiff:i.screenY-n.screenY}}async dragWithMoveTo(t,r,n,i,o){return await this.moveTo(t,i,o),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,i,o){let a=this.getMoveActions(i,o,t,1),c=this.getClickActions(["pointerDown"],mr),l=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],mr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(c).concat(l).concat(d)}])}async drag(t,r,n,i,o){let{width:a,height:c}=r,l=n-a/2+1,d=i-c/2,m=this.getDragCoordinates(o),{xDiff:u,yDiff:f}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,l,d);try{return await this.dragWithMoveTo(t,u,f,l,d)}catch(h){if(je(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,l,d);throw h}}getMoveRelativeSequence(t,r,n,i){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},c={x:n,y:i},l=10,d=Math.round(o(a,c)/l),m=Array.from({length:d},()=>({x:Math.round((c.x-a.x)/d),y:Math.round((c.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,i){return this.getMoveRelativeSequence(t,r,n,i).reduce((a,c)=>{let l=a.at(-1);return a.concat({x:Math.round(l.x+c.x),y:Math.round(l.y+c.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:i,fromX:o,fromY:a,toRect:c,toX:l,toY:d}=n,m=Mr().calculateElementMiddlePoint(i),u=Mr().calculateElementMiddlePoint(c),f=this.getMoveRelativeSequence(m.x+o,m.y+a,u.x+l,u.y+d);await this.moveTo(t,Math.floor(o),Math.floor(a)),await this.buttonDown();for(let h of f)await this.moveTo(null,h.x,h.y);return await this.moveTo(r,Math.round(l),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:c}=t,l=Mr().calculateElementMiddlePoint(r),d=Mr().calculateElementMiddlePoint(o),m=Math.floor(l.x+n),u=Math.floor(l.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+c),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),w=this.getClickActions(["pointerDown"],mr),S=Cs.flatMap(g,C=>this.getMoveActions(C.x,C.y)),b=this.getMoveActions(f,h),v=this.getClickActions(["pointerUp"],mr),T=y.concat(w).concat(S).concat(b).concat(v);return this.actions([{type:"pointer",id:"mouse",actions:T}])}async dragAndDrop(t,r,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,r,n)}catch(i){if(je(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw i}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(i){if(je(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw i}}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(i){if(je(i))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw i}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:c}=t,l=Mr().calculateElementMiddlePoint(r),d=Mr().calculateElementMiddlePoint(o),m=Math.floor(l.x+n),u=Math.floor(l.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+c);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],mr);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],mr);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(wh(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(i){$e.error("error getting element location",{err:i})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){$e.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||$e.warn("failed to close session because session is undefined"),this.stopKeepAliveInterval();try{return await super.end()}catch{return}}async submit(t){if(this.unsupportedActions.has("submit"))return await super.submitFormManually(t);try{return await super.submitForm(t)}catch(r){if(je(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var Pu,ku,Jn,Ou=I(()=>{"use strict";W();me();ye();Pu=A("lab-features-service"),ku=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(Pu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await _u(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){Pu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=O.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:i}=this,o=n.find(c=>c.featureFlagName===e),a=o==null?void 0:o.enabled;return Boolean(i&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw Pu.error(t,{featureFlagName:e.name}),new Error(t)}},Jn=new ku});function mE(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function fE(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:r}=globalThis.require("path"),{promises:n}=globalThis.require("fs");return{sync:!1,lib:n.readFile(`${s}${t}package.json`).then(o=>{let a=JSON.parse(o);return import(r(s,a.main||`${t}index.js`))})}}}function gE(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function hE(s,e,t,r,n={},i=void 0,o=void 0){let a=Object.keys(n).map(h=>`
44
+ `,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,Rs,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,lE,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(Bt(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw n}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(n){if(Bt(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw n}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:i}=r.clickOffset;try{return await this.moveTo(t,n,i)}catch(o){if(Bt(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,n="viewport",i=0){return[{type:"pointerMove",duration:i,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){He.error("tried to use element origin but failed because of visibility, trying location",n);let i=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(i)}}getMoveRelativeSequence(t,r,n,i){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},c={x:n,y:i},l=10,d=Math.round(o(a,c)/l),m=Array.from({length:d},()=>({x:Math.round((c.x-a.x)/d),y:Math.round((c.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,i){return this.getMoveRelativeSequence(t,r,n,i).reduce((a,c)=>{let l=a.at(-1);return a.concat({x:Math.round(l.x+c.x),y:Math.round(l.y+c.y)})},[{x:Math.round(t),y:Math.round(r)}])}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:c}=t,l=zn().calculateElementMiddlePoint(r),d=zn().calculateElementMiddlePoint(o),m=Math.floor(l.x+n),u=Math.floor(l.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+c),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),w=this.getClickActions(["pointerDown"],Rs),S=xs.flatMap(g,C=>this.getMoveActions(C.x,C.y)),b=this.getMoveActions(f,h),v=this.getClickActions(["pointerUp"],Rs),T=y.concat(w).concat(S).concat(b).concat(v);return this.actions([{type:"pointer",id:"mouse",actions:T}])}async dragAndDrop(t){return this.isSafari()?this.dragAndDropWithActionsAPIWithGeneratedMoves(t):this.dragAndDropWithActionsAPI(t)}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(i){if(Bt(i))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw i}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:c}=t,l=zn().calculateElementMiddlePoint(r),d=zn().calculateElementMiddlePoint(o),m=Math.floor(l.x+n),u=Math.floor(l.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+c);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],Rs);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],Rs);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(wh(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(i){He.error("error getting element location",{err:i})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){He.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||He.warn("failed to close session because session is undefined"),this.stopKeepAliveInterval();try{return await super.end()}catch{return}}async submit(t){return super.submitFormManually(t)}}});var Pu,ku,Jn,Ou=I(()=>{"use strict";W();me();ye();Pu=A("lab-features-service"),ku=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(Pu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await _u(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){Pu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=O.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:i}=this,o=n.find(c=>c.featureFlagName===e),a=o==null?void 0:o.enabled;return Boolean(i&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw Pu.error(t,{featureFlagName:e.name}),new Error(t)}},Jn=new ku});function mE(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function fE(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:r}=globalThis.require("path"),{promises:n}=globalThis.require("fs");return{sync:!1,lib:n.readFile(`${s}${t}package.json`).then(o=>{let a=JSON.parse(o);return import(r(s,a.main||`${t}index.js`))})}}}function gE(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function hE(s,e,t,r,n={},i=void 0,o=void 0){let a=Object.keys(n).map(h=>`
45
45
  var res = requireOrImportMethod('${mE(n[h])}');
46
46
  if (res.sync) {
47
47
  var ${h} = res.lib;
@@ -209,24 +209,24 @@ Testim had missing write access to ${r||e}
209
209
  injectCode(params, args, incomingParams, context, code);
210
210
  });
211
211
  })();
212
- `,u=[],f=new Ah.Worker(m,{eval:!0});try{return await pe(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,w={...y,tstConsoleLogs:u};ht.debug("Run code worker response",{messageWithLogs:w,transactionId:s}),h(w)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?ht.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):ht.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{ht.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),i)}catch(h){if(!(h instanceof ue))throw h;return ht.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function yE(s){try{await Rh.promises.rm(s,{recursive:!0,force:!0})}catch(e){ht.warn("failed to remove install npm packages folder",{err:e})}}function Ph(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function Ps(s,e,t,r,n,i){let o=Ph(n,e,s,t),{data:a}=await bE(o,r,i);return a}async function ks(s,e,t,r,n,i,o,a,c,l){var g;let d=r.computePackagePathFromPackageJsonExports||O.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let w=ff(y.testimPackageLocalLocation);return[y.paramName,As.join(y.testimPackageLocalLocation,w)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=Ph(o,n,e,i);if(l){let y=await Bn(l);y&&(c=y)}Buffer.isBuffer(c)&&(ht.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let f="data:,";return c==="data:"&&(ht.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=f),{...await hE(u,t,r,s,m,a,c),nodeVersion:process.version}}async function bE(s,e,t){let r=e.map(l=>`${l.packageName}@${l.packageVersion}`),n=kh(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?n:As.join(n,`/${s}`),a=global.proxyUri;async function c(){let l="";try{if(l=await ml(o,r,a,t),ht.info("npm package install finished",{transactionId:s,output:l,timeout:t}),Number(l.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=df(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:As.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw ht.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await pe(c(),t)}catch(l){throw l instanceof ue&&ht.warn("timeout to install package",{packages:r,transactionId:s,err:l,timeout:t}),l}}function kh(){return As.join(xh.tmpdir(),"/testim_local_packages")}function TE(){let s=kh();return yE(s)}var Rh,xh,As,Ch,Ah,ht,Os=I(()=>{"use strict";Rh=R(require("fs")),xh=R(require("os")),As=R(require("path"));F();ds();Ch=R(require("data-uri-to-buffer")),Ah=require("worker_threads");Q();W();ye();ds();me();ht=A("cli-service");TE().catch(s=>ht.warn("failed to clean local package folder",{err:s}))});var fr={};z(fr,{run:()=>vE});function wE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var vE,Oh=I(()=>{"use strict";Os();Q();me();vE=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await ks(r,n,i,o,a,c,l,d,m,u);return f&&wE({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ue?new Error("Timeout while running action"):f}}});var Lu={};z(Lu,{run:()=>SE});var SE,_h=I(()=>{"use strict";Os();Q();SE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await Ps(t,r,n,o,i,a),success:!0}}catch(c){if(c instanceof Nt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof ue)return{success:!1,code:"timeout"};throw c}}});async function Dh(s,e,t,r){try{return await Du(s,e,t,r)}catch{zo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function IE(s,e,t,r,n){return zo.info("finished to run remote step",{stepId:t,sessionId:n}),await Dh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Lh(s,e,t,r,n){return zo.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Dh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Nh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),c=t.id;zo.info("start play remote step",{stepType:o,stepId:c,sessionId:a});let l=EE[o];if(!l)return await Lh(n,r,c,`Failed to find step type ${o}`,a);try{let d=await l.run(e,t,i);return await IE(n,r,c,d,a)}catch(d){return await Lh(n,r,c,d.message,a)}}var zo,EE,Mh=I(()=>{"use strict";Oh();ye();_h();W();zo=A("step-playback"),EE={"cli-validation-code-step":fr,"cli-wait-for-code-step":fr,"cli-action-code-step":fr,"cli-api-code-step":fr,"cli-condition-step":fr,"cli-download-code-step":fr,"node-package":Lu}});var Uh={};z(Uh,{preloadTests:()=>Yn});async function Yn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await pt(async()=>{let t=await oe(s.testId,r=>Qn({...e,testId:r}),{concurrency:2});return Fh.keyBy(t,"testData.id")},"loadTests",xE,[e,s.testId])()}var Fh,xE,Ko=I(()=>{"use strict";Fh=R(require("lodash"));Jt();ye();F();xE=1e3*60*60*10});var Nu,Bh,Ur,CE,Mu,xt,Jo=I(()=>{"use strict";F();mt();Nu=R(require("ws")),Bh=require("events");W();le();Ur=A("socket-service"),CE=5e3,Mu=class extends Bh.EventEmitter{constructor(){super(...arguments);this.clientId=ne();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Ur.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),CE)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Ur.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(zd);return Ft().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Nu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return Ur.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{Ur.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Nu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Ur.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){Ur.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Ur.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(c){n(c)&&i(c)}(Array.isArray(r)?r:[r]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=o.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=ne(),c={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",l=>l.id===a,o),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},xt=new Mu});var $h,Fu,AE,PE,kE,jh,Xo,_s,Uu=I(()=>{"use strict";$h=R(require("p-retry")),Fu=R(require("socket.io-client"));le();F();W();AE=50,PE=10,kE=5e3,jh=10*1e3,Xo=A("base socket service"),_s=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Xo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Xo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===PE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=AE)throw new Error(`Can't connect to Testim Servers.
213
- Action required: Please allow opening a websockets connection to ${be()} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Xo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:jh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${be()}/${t}`,this._socket=Fu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:jh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${be()}/${t}`,this._socket=Fu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,$h.default)(()=>pe(n(),kE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Xo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Wh={};z(Wh,{remoteStepServiceSocketIO:()=>OE});var Bu,OE,Vh=I(()=>{"use strict";Uu();Bu=class extends _s{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},OE=new Bu});var Gh={};z(Gh,{remoteStepService:()=>Ls});var ju,Zn,$u,Ls,Yo=I(()=>{"use strict";Jo();ae();me();({REMOTE_STEP_SAVED:ju}=Mt),$u=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Zn=(await Promise.resolve().then(()=>(Vh(),Wh))).remoteStepServiceSocketIO,Zn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?xt.addFilter(`${e}:remoteStep`,{resultId:e},[ju]):Zn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){xt.listenTo(`${e}:remoteStep`,[ju],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Zn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(xt.removeFilter(`${e}:remoteStep`,[ju]),Promise.resolve()):Zn.unlistenToRemoteStep(e)}},Ls=new $u});var Wu,Br,Hh=I(()=>{"use strict";Uu();Wu=class extends _s{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Br=new Wu});var zh={};z(zh,{testResultService:()=>jt});var qh,Vu,jt,Qo=I(()=>{"use strict";qh=require("events");Jo();ae();me();Hh();Vu=class extends qh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){xt.onConnect=()=>this.emit("socket-connected");return}Br.init(e),Br.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?xt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Mt.TEST_RESULT_UPDATED,Mt.TEST_RESULT_CREATED]):Br.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){xt.removeFilter(`${e}:testResult`,[Mt.TEST_RESULT_UPDATED,Mt.TEST_RESULT_CREATED]);return}await Br.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){xt.listenTo(`${e}:testResult`,[Mt.TEST_RESULT_UPDATED,Mt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Br.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Br.getSocket()}},jt=new Vu});var Jh,Xh,Yh,Re,_E,Qh,Kh,LE,Zo,Zh=I(()=>{"use strict";Jh=R(require("lodash"));F();le();Ve();kr();mt();ye();Mh();Xh=R(require("p-retry")),Yh=require("node:url");W();Ko();Es();ae();Yo();Qo();ye();Re=A("test-run-handler"),_E=3,Qh=20*1e3,Kh=s=>JSON.stringify(s).length<Qh,LE="Test couldn't be started",Zo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new _r;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l,d;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId,this._customCapabilities=n.customCapabilities||((l=r.customCapabilities)==null?void 0:l.capabilities);let a=!((d=r.runConfig)!=null&&d.isMobileWeb)&&n.browser;this._runConfig=a?pn(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get nativeApp(){return this._nativeApp}get executionName(){return this._executionName}get customCapabilities(){return this._customCapabilities}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return un(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return rs(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Wi.FROM_DEVICE:Wi.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${be()}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async isTestRecordedWithEnhancedMode(){return(await Qn({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await Ft(),refreshToken:lo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:em(),remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await uo()};if(this._options.disableMockNetwork&&gt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Kh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,c=this.testId;o?(Object.assign(t,{runData:i}),Re.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Re.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Qh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let i=await Yn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Re.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testOptimization(){return this._testOptimization}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Kh(e))return;let r=async()=>{try{return await qu(this._options.project,this._testId,this._testResultId,e)}catch(o){return Re.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Hu(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===LE||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){M("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=o||{};M("before Runtime.evaluate"),await(0,Xh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return M("after Runtime.evaluate"),l.value}catch(o){throw Re.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Yh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){Re.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(Re.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:c,branch:l,_options:{project:d}}=this;try{let m=await jr(a,c,d,l);n(m),r||setTimeout(o,3e3)}catch(m){Re.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else jt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await jr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Re.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Re.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Pe.TEST_START_TIMEOUT_MSG)}catch(i){throw Re.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Pe.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await jt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Re.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||jt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Re.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Jh.debounce(async()=>{try{await jt.joinToTestResult(this._testResultId,this.testId)}catch(o){Re.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await jr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Re.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(Re.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return Re.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)jt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Gu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Re.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Re.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&jt.off("socket-connected",e)}}listenToRemoteStep(e){Ls.listenToRemoteStep(this.testResultId,t=>{Nh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:_E;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=ne(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var ea,ey=I(()=>{"use strict";Zh();ea=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new Zo(e,t,c,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function ry(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:ne()}))]}:await Ju({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function zu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Ku(s,e){let t=s.mode===J.EXTENSION?$r:ei,r=ty.difference(cn(s,e),t);if(r.length>0)throw gt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new x(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var ty,$r,ei,ta=I(()=>{"use strict";ty=R(require("lodash"));F();kr();ye();Q();ae();$r=["edge-chromium","chrome"],ei=[...$r,"firefox","safari","safari technology preview"]});var DE,NE,ME,ti,Xu=I(()=>{"use strict";fs();Ts();W();DE=A("worker-utils"),NE=async(s,e,t)=>{e&&await Ol(s,t)},ME=async(s,e,t)=>{await su(s,e,t)},ti=async(s,e,t,r,n,i)=>{DE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await NE(s,e,t),n==="redis"&&await ME(s,r,t)}}});function jE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var na,iy,ia,oa,oy,Ct,sy,ny,ra,Yu,Wr,FE,Qu,UE,Qt,BE,sa,$E,$t,ri=I(()=>{"use strict";na=R(require("ms")),iy=R(require("lodash")),ia=R(require("p-retry")),oa=R(require("dayjs")),oy=R(require("dayjs/plugin/duration"));F();Ve();fs();Ts();ye();W();Xu();Bt();jo();me();Yo();Qo();mt();qe();ae();Q();oa.default.extend(oy.default);Ct=A("base-worker"),{GET_BROWSER_TIMEOUT_MSG:sy,TEST_START_TIMEOUT_MSG:ny,TEST_COMPLETE_TIMEOUT_MSG:ra,TEST_REACHED_CUSTOM_TIMEOUT_MSG:Yu}=Pe,{SETUP_TIMEOUT:Wr,NETWORK_ERROR:FE,GRID_ERROR:Qu,BROWSER_CLOSED:UE,SELENIUM_ERROR:Qt,UNKNOWN_ERROR:BE,MOBILE_SESSION_ERROR:sa}=Zr;$E=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],$t=class{constructor(e,t,r,n,i,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new ce;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await Vf(e,t.executionId,this.options,this.id,t.testResultId);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Z.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new en(!0)}async getBrowserOnce(e,t,r,n){throw new en(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),Ct.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!tt({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:he.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=ss(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:he.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=O.flags.increaseTDCRequestTimeout.isEnabled(),r=Ir(O.flags.appiumConnectionRequestTimeout.getValue(),(0,na.default)("2m")),n=Ir(O.flags.appiumConnectionRetryCount.getValue(),1),i=r*n;return e===N.BROWSERSTACK||t&&e===N.TESTIM_TDC?i+(0,na.default)("10m"):i+(0,na.default)("1m")}getSessionTimeout(){if(ir(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,ia.default)(async()=>{let n=Date.now();try{return await pe(this.getSlotOnce(e),this.options.getBrowserTimeout,Pe.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,ia.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await pe(gg(o,a,this.id),this.options.getBrowserTimeout,Pe.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof sr?Ct.info("could not get grid slot due to concurrency issue",r):Ct.error("error getting grid slot",{error:e,...r}),await ie(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let c=this.options.getBrowserRetries-o;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,ia.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await Gf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=l,M("before getBrowserOnce");let f=await pe(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Pe.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Z.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:l,id:this.options.gridData.gridId},h=this.options.mode===J.APPIUM?"device":"browser";throw Ct.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,r,++l),m.onDone(),!(u instanceof Dt)&&this.options.mode!==J.APPIUM&&await ie(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:c-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(o){throw await ti(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Dt,Xr].some(a=>o instanceof a)?o:o instanceof ct?new Sr(o,Qu):new Sr(o,Qt)}return n}async runTest(e,t,r){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=ir(this.options)&&this.handleMobileTest(e);if(o)return o;M("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await Ft(),await this.runTestOnce(e,l)}finally{await ti(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var D,j;if(tt(g,this.options)||ss(O,(D=this.options.gridData)==null?void 0:D.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let w=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let S=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof Sr,v=S(ny),T=y&&(S(ra)||S(Yu)||v&&!e.retryOnInfraErrors),C=!!S(Yu)&&!!this.testRunTimeout,B=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||v)&&e.retryOnInfraErrors,G=T&&e.hasMoreTimeoutRetries()&&!C,E=e.hasMoreRetries()&&!b&&!T,k=!g.success&&(E||G||B);try{let V=e.retryKey;g.testRetryKey=V;let K=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,w,k,K),await this.runTestCleanup(),k){if(G&&await e.startNewTimeoutRetry(),B){Ct.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:y});let q=(j=this.options.projectData)==null?void 0:j.projectId,re=e.testResultId,ge=e.testId;await aa(q,re,ge,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return E&&!B&&!G&&await e.startNewRetry(),Ct.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:T,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(k)}t(this.id,...r);return}catch(V){if(V instanceof rr)return;Ct.error("failed to process test result",{error:V}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
214
- Please make sure the CLI has stable access to the internet. ${jc()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:w,APP_NEVER_STARTED:S,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:v}=Qc,T=g instanceof Error?g.message:g;if(T.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),T.includes(sy)||T.includes(b))return{errorType:Wr,reason:"timeout while getting device"};if(T.includes(ra)||T.includes(Yu)){if(!this.testRunTimeout)return{errorType:Wr,reason:"Test timeout reached!"};let C=oa.default.duration({milliseconds:this.testRunTimeout});return{errorType:Wr,reason:`Test timeout reached (timeout: ${Hi(C)})`}}return T.includes(w)||T.includes(v)?{errorType:sa,reason:"app doesn't exist on device"}:T.includes(S)?{errorType:sa,reason:"app never started, check app permission or app activity"}:T.includes(y)?{errorType:sa,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:sa,reason:T}},a=(g,y)=>{let w=this.options.mode===J.APPIUM?"device":"browser";if(!y&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:FE,reason:i()};let S=g instanceof Error?g.message:g;if(S.includes(sy))return{errorType:Wr,reason:`Test couldn't get ${w}`};if(S.includes(ny))return{errorType:Wr,reason:"Test couldn't be started"};if(g instanceof Sr&&g.type){if(g.type===Qu)return{errorType:Qu,reason:`Test couldn't get ${w} from grid - ${g.message}`};if(g.type===Qt)return{errorType:Qt,reason:`Failed to create new session - ${g.message}`}}return S.includes(ra)?this.testRunTimeout?{errorType:Wr,reason:`Test timeout reached (timeout: ${Hi(oa.default.duration({milliseconds:this.testRunTimeout}))})`}:{errorType:Wr,reason:"Test timeout reached: test is too long"}:"type"in g&&g.type===UE?{errorType:Qt,reason:`Session terminated, this is often caused to connection
215
- problems between the Testim CLI and the grid running the test. Please check your network connection.`}:"type"in g&&g.type==="KEEP_ALIVE_FAILED"?{errorType:Qt,reason:"Test terminated due to repeated keep alive failures. The browser may have become unresponsive or the test environment may be unstable."}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:Qt,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:Qt,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:Qt,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:Qt,reason:`Session could not be created, please check that the ${w} you requested is supported in your plan`}:{errorType:BE,reason:S}},c=async g=>{var v;let y=await Bc();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),Ct.warn("error on run",{err:g});let w=(v=this.userData)==null?void 0:v.projectId,{errorType:S,reason:b}=this.options.mode===J.APPIUM?o(g):a(g,y);aa(w,this.testResultId,this.testId,{status:on.COMPLETED,success:!1,reason:b,errorType:S,testRetryKey:e.retryKey,setupStepResult:{status:on.COMPLETED,success:!1,reason:b,errorType:S}},e.remoteRunId),await n(jE(this.testId,this.testName,this.testResultId,b),g)},l=async g=>{var v;let y=this.testId,w=this.testResultId,S=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!w||!S||!b)return Ct.warn("Test failed. Not enough data to recover results via API",{err:g}),c(g);try{let T=await jr(y,w,S,b);if(Ct.warn("Test failed. Got results via API",{err:g,testResult:iy.default.omit(T,$E),resultId:w}),T&&T.status===on.COMPLETED&&!g.message.includes(ra))return await n(T);throw g}catch(T){return T!==g&&Ct.error("Failed to fetch test results from server",{testId:y,resultId:w,projectId:S,branch:b,err:T}),c(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===J.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&Ls.joinToRemoteStep(this.testResultId),!d&&jt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==J.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),M("After onRunComplete"),t(this.id,...r)}catch(y){await l(y),t(this.id,...r)}finally{m||Ls.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,u()}}});var cy,ay,Ds,Zu=I(()=>{"use strict";F();cy=R(require("p-retry"));F();W();Q();ay=A("window-utils"),Ds=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return ay.warn("selenium navigation failed. retrying to navigate",{err:i}),await ie(1500),r(n-1);throw!i.seleniumStack&&o&&ay.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),ie(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ie(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ie(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&!r.href.startsWith("res://ieframe.dll/http_404.htm")&&!r.href.startsWith("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")}if(!(await this.driver.executeJS(e)).value)throw new Dt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,cy.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var ep,Ns,tp=I(()=>{"use strict";W();ep=A("cookies-utils"),Ns=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw ep.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw ep.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw ep.error("failed to remove cookie",{err:t}),t}}}});var rp,ca,ly=I(()=>{"use strict";rp=R(require("p-retry")),ca=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[i,o]=await(0,rp.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,rp.default)(i,{retries:t,minTimeout:r,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function WE(s){let{loadImage:e}=await Ue("canvas"),t=Buffer.from(s,"base64");return await e(t)}async function la(s){let e=await WE(s);return{width:e.width,height:e.height}}async function uy(s,e){let{createCanvas:t,Image:r}=await Ue("canvas"),n=t(e.width,e.height),i=n.getContext("2d"),o=new r;return o.src=`data:image/png;base64,${s}`,await new Promise((a,c)=>{o.onload=()=>a(),o.onerror=c}),i.drawImage(o,e.left,e.top,e.width,e.height,0,0,e.width,e.height),n.toDataURL("image/png")}async function py(s,e){let t="image/png",{createCanvas:r,Image:n}=await Ue("canvas"),i=r(s.width,s.height),o=i.getContext("2d");for(let c of e){let l=c.image.match(/^data:([^;]*);base64,(.*)$/),d=l[1],m=l[2],u=new n;u.src=`data:${d};base64,${m}`,await new Promise((f,h)=>{u.onload=()=>f(),u.onerror=h}),o.drawImage(u,c.position.left,c.position.top,c.size.width,c.size.height)}return i.toDataURL(t)}var sp=I(()=>{"use strict";Ss()});async function dy(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let i=s.offset||{top:0,left:0};if(i.top*=r,i.left*=r,!s.elementRect)return VE.warn("missing elementRect",fy.omit(s,"image")),{};let{elementRect:o}=s,a=o.left*r+i.left*r,c=o.top*r+i.top*r,l=o.width*r,d=o.height*r;a<0&&(l+=a,l=Math.max(l,0),a=0),c<0&&(d+=c,d=Math.max(d,0),c=0);let{width:m,height:u}=await la(n[1]);if(a+l>m&&(l=m-a),c+d>u&&(d=u-c),d<=0||l<=0)throw new np("height or width is equal or lower than zero");return{elementImage:await uy(n[1],{left:a,top:c,width:l,height:d})}}function GE(s,e){return py(s,e)}async function HE(){}async function qE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await HE(s[i]);return{key:i,url:o}}let r=await oe(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function my(s,e){return e||=1,s||={left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var fy,VE,np,ua,gy=I(()=>{"use strict";fy=R(require("lodash"));F();sp();W();VE=A("image-capture-utils"),np=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};ua=class{constructor(e,t,r){this.windowUtils=t;this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),r=await dy(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:my(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return qE({screenImage:t.image,absoluteScreenHighlight:my(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>ie(250),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await dy({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await o(h.scrollPos,h.cropData);f.push(g)}return f}function c(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),w=f.height,S=Array.from({length:Math.ceil(h/g)},(v,T)=>({scrollX:Math.min(T*g,h-g),cropX:T*g-Math.min(T*g,h-g),cropW:g-(T*g-Math.min(T*g,h-g))})),b=Array.from({length:Math.ceil(y/w)},(v,T)=>({scrollY:Math.min(T*w,y-w),cropY:T*w-Math.min(T*w,y-w),cropH:w-(T*w-Math.min(T*w,y-w))}));return S.flatMap(v=>b.map(T=>({scrollPos:{x:v.scrollX,y:T.scrollY},cropData:{top:T.cropY,left:v.cropX,width:v.cropW,height:T.cropH}})))}async function l(u,f){let h=await t.getCurrentScrollPosition(),g=c(u,f),y=await a(g);return await t.scrollToPosition(h),GE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(d,m)}}});var hy,yy,pa,da,by=I(()=>{"use strict";hy=R(require("p-retry")),yy=R(require("semver"));F();W();Zu();ly();gy();Se();pa=A("tab-service"),da=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),pa.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=ne();function c(l){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!l.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Ds(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new ua(t,a,new ca(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=ee(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),c=n(o),l=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===c);return c===l&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=ee();if(n){let l=this.getAllTabInfos(e),d=Object.keys(l).map(m=>l[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(l=>i[l].url);if(this.exactUrlMatch(t,r,o))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,o,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){pa.error("failed to get url or title",{err:i})}}catch(n){pa.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ie(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){pa.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let i=await this.waitForTabToOpen(e);await this.addNewTab(e,i,this.pendingTabs[e]),this.addFrameHandler(i),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,hy.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=yy.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var c,l;let{tabMatcher:r,commonConstants:n}=ee();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((c=t.useCurrentTab)!=null&&c.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(l=t.tabInfo)==null?void 0:l.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var ip,ma,op=I(()=>{"use strict";ip=class{select(){return console.log(`
212
+ `,u=[],f=new Ah.Worker(m,{eval:!0});try{return await le(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,w={...y,tstConsoleLogs:u};gt.debug("Run code worker response",{messageWithLogs:w,transactionId:s}),h(w)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?gt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):gt.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{gt.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),i)}catch(h){if(!(h instanceof pe))throw h;return gt.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function yE(s){try{await Rh.promises.rm(s,{recursive:!0,force:!0})}catch(e){gt.warn("failed to remove install npm packages folder",{err:e})}}function Ph(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function As(s,e,t,r,n,i){let o=Ph(n,e,s,t),{data:a}=await bE(o,r,i);return a}async function Ps(s,e,t,r,n,i,o,a,c,l){var g;let d=r.computePackagePathFromPackageJsonExports||O.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let w=ff(y.testimPackageLocalLocation);return[y.paramName,Cs.join(y.testimPackageLocalLocation,w)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=Ph(o,n,e,i);if(l){let y=await Un(l);y&&(c=y)}Buffer.isBuffer(c)&&(gt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let f="data:,";return c==="data:"&&(gt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=f),{...await hE(u,t,r,s,m,a,c),nodeVersion:process.version}}async function bE(s,e,t){let r=e.map(l=>`${l.packageName}@${l.packageVersion}`),n=kh(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?n:Cs.join(n,`/${s}`),a=global.proxyUri;async function c(){let l="";try{if(l=await ml(o,r,a,t),gt.info("npm package install finished",{transactionId:s,output:l,timeout:t}),Number(l.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=df(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:Cs.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw gt.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await le(c(),t)}catch(l){throw l instanceof pe&&gt.warn("timeout to install package",{packages:r,transactionId:s,err:l,timeout:t}),l}}function kh(){return Cs.join(xh.tmpdir(),"/testim_local_packages")}function TE(){let s=kh();return yE(s)}var Rh,xh,Cs,Ch,Ah,gt,ks=I(()=>{"use strict";Rh=R(require("fs")),xh=R(require("os")),Cs=R(require("path"));F();us();Ch=R(require("data-uri-to-buffer")),Ah=require("worker_threads");Q();W();ye();us();me();gt=A("cli-service");TE().catch(s=>gt.warn("failed to clean local package folder",{err:s}))});var mr={};z(mr,{run:()=>vE});function wE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var vE,Oh=I(()=>{"use strict";ks();Q();me();vE=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await Ps(r,n,i,o,a,c,l,d,m,u);return f&&wE({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof pe?new Error("Timeout while running action"):f}}});var Lu={};z(Lu,{run:()=>SE});var SE,_h=I(()=>{"use strict";ks();Q();SE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await As(t,r,n,o,i,a),success:!0}}catch(c){if(c instanceof Dt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof pe)return{success:!1,code:"timeout"};throw c}}});async function Dh(s,e,t,r){try{return await Du(s,e,t,r)}catch{zo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function IE(s,e,t,r,n){return zo.info("finished to run remote step",{stepId:t,sessionId:n}),await Dh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Lh(s,e,t,r,n){return zo.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Dh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Nh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),c=t.id;zo.info("start play remote step",{stepType:o,stepId:c,sessionId:a});let l=EE[o];if(!l)return await Lh(n,r,c,`Failed to find step type ${o}`,a);try{let d=await l.run(e,t,i);return await IE(n,r,c,d,a)}catch(d){return await Lh(n,r,c,d.message,a)}}var zo,EE,Mh=I(()=>{"use strict";Oh();ye();_h();W();zo=A("step-playback"),EE={"cli-validation-code-step":mr,"cli-wait-for-code-step":mr,"cli-action-code-step":mr,"cli-api-code-step":mr,"cli-condition-step":mr,"cli-download-code-step":mr,"node-package":Lu}});var Uh={};z(Uh,{preloadTests:()=>Yn});async function Yn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ut(async()=>{let t=await oe(s.testId,r=>Qn({...e,testId:r}),{concurrency:2});return Fh.keyBy(t,"testData.id")},"loadTests",xE,[e,s.testId])()}var Fh,xE,Ko=I(()=>{"use strict";Fh=R(require("lodash"));Xt();ye();F();xE=1e3*60*60*10});var Nu,Bh,Mr,CE,Mu,Rt,Jo=I(()=>{"use strict";F();dt();Nu=R(require("ws")),Bh=require("events");W();ue();Mr=A("socket-service"),CE=5e3,Mu=class extends Bh.EventEmitter{constructor(){super(...arguments);this.clientId=ne();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Mr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),CE)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Mr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(zd);return Mt().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Nu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return Mr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{Mr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Nu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Mr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){Mr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Mr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(c){n(c)&&i(c)}(Array.isArray(r)?r:[r]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=o.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=ne(),c={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",l=>l.id===a,o),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},Rt=new Mu});var $h,Fu,AE,PE,kE,jh,Xo,Os,Uu=I(()=>{"use strict";$h=R(require("p-retry")),Fu=R(require("socket.io-client"));ue();F();W();AE=50,PE=10,kE=5e3,jh=10*1e3,Xo=A("base socket service"),Os=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Xo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Xo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===PE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=AE)throw new Error(`Can't connect to Testim Servers.
213
+ Action required: Please allow opening a websockets connection to ${be()} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Xo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:jh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${be()}/${t}`,this._socket=Fu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:jh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${be()}/${t}`,this._socket=Fu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,$h.default)(()=>le(n(),kE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Xo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Wh={};z(Wh,{remoteStepServiceSocketIO:()=>OE});var Bu,OE,Vh=I(()=>{"use strict";Uu();Bu=class extends Os{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},OE=new Bu});var Gh={};z(Gh,{remoteStepService:()=>_s});var ju,Zn,$u,_s,Yo=I(()=>{"use strict";Jo();ae();me();({REMOTE_STEP_SAVED:ju}=Nt),$u=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Zn=(await Promise.resolve().then(()=>(Vh(),Wh))).remoteStepServiceSocketIO,Zn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?Rt.addFilter(`${e}:remoteStep`,{resultId:e},[ju]):Zn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){Rt.listenTo(`${e}:remoteStep`,[ju],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Zn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(Rt.removeFilter(`${e}:remoteStep`,[ju]),Promise.resolve()):Zn.unlistenToRemoteStep(e)}},_s=new $u});var Wu,Fr,Hh=I(()=>{"use strict";Uu();Wu=class extends Os{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Fr=new Wu});var zh={};z(zh,{testResultService:()=>$t});var qh,Vu,$t,Qo=I(()=>{"use strict";qh=require("events");Jo();ae();me();Hh();Vu=class extends qh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){Rt.onConnect=()=>this.emit("socket-connected");return}Fr.init(e),Fr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?Rt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Nt.TEST_RESULT_UPDATED,Nt.TEST_RESULT_CREATED]):Fr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){Rt.removeFilter(`${e}:testResult`,[Nt.TEST_RESULT_UPDATED,Nt.TEST_RESULT_CREATED]);return}await Fr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){Rt.listenTo(`${e}:testResult`,[Nt.TEST_RESULT_UPDATED,Nt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Fr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Fr.getSocket()}},$t=new Vu});var Jh,Xh,Yh,Re,_E,Qh,Kh,LE,Zo,Zh=I(()=>{"use strict";Jh=R(require("lodash"));F();ue();$e();Pr();dt();ye();Mh();Xh=R(require("p-retry")),Yh=require("node:url");W();Ko();vs();ae();Yo();Qo();ye();Re=A("test-run-handler"),_E=3,Qh=20*1e3,Kh=s=>JSON.stringify(s).length<Qh,LE="Test couldn't be started",Zo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Or;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l,d;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId,this._customCapabilities=n.customCapabilities||((l=r.customCapabilities)==null?void 0:l.capabilities);let a=!((d=r.runConfig)!=null&&d.isMobileWeb)&&n.browser;this._runConfig=a?un(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get nativeApp(){return this._nativeApp}get executionName(){return this._executionName}get customCapabilities(){return this._customCapabilities}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return ln(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return es(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Wi.FROM_DEVICE:Wi.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${be()}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async isTestRecordedWithEnhancedMode(){return(await Qn({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await Mt(),refreshToken:lo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:em(),remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await uo()};if(this._options.disableMockNetwork&&ft("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Kh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,c=this.testId;o?(Object.assign(t,{runData:i}),Re.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Re.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Qh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let i=await Yn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Re.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testOptimization(){return this._testOptimization}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Kh(e))return;let r=async()=>{try{return await qu(this._options.project,this._testId,this._testResultId,e)}catch(o){return Re.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Hu(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===LE||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){M("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=o||{};M("before Runtime.evaluate"),await(0,Xh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return M("after Runtime.evaluate"),l.value}catch(o){throw Re.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Yh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){Re.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(Re.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:c,branch:l,_options:{project:d}}=this;try{let m=await Ur(a,c,d,l);n(m),r||setTimeout(o,3e3)}catch(m){Re.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else $t.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Ur(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Re.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Re.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Pe.TEST_START_TIMEOUT_MSG)}catch(i){throw Re.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Pe.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await $t.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Re.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||$t.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Re.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Jh.debounce(async()=>{try{await $t.joinToTestResult(this._testResultId,this.testId)}catch(o){Re.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Ur(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Re.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(Re.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return Re.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)$t.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Gu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Re.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Re.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&$t.off("socket-connected",e)}}listenToRemoteStep(e){_s.listenToRemoteStep(this.testResultId,t=>{Nh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:_E;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=ne(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var ea,ey=I(()=>{"use strict";Zh();ea=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new Zo(e,t,c,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function ry(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:ne()}))]}:await Ju({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function zu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Ku(s,e){let t=s.mode===J.EXTENSION?Br:ei,r=ty.difference(an(s,e),t);if(r.length>0)throw ft("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new x(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var ty,Br,ei,ta=I(()=>{"use strict";ty=R(require("lodash"));F();Pr();ye();Q();ae();Br=["edge-chromium","chrome"],ei=[...Br,"firefox","safari","safari technology preview"]});var DE,NE,ME,ti,Xu=I(()=>{"use strict";ds();ys();W();DE=A("worker-utils"),NE=async(s,e,t)=>{e&&await Ol(s,t)},ME=async(s,e,t)=>{await su(s,e,t)},ti=async(s,e,t,r,n,i)=>{DE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await NE(s,e,t),n==="redis"&&await ME(s,r,t)}}});function jE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var na,iy,ia,oa,oy,xt,sy,ny,ra,Yu,jr,FE,Qu,UE,Qt,BE,sa,$E,Wt,ri=I(()=>{"use strict";na=R(require("ms")),iy=R(require("lodash")),ia=R(require("p-retry")),oa=R(require("dayjs")),oy=R(require("dayjs/plugin/duration"));F();$e();ds();ys();ye();W();Xu();Ut();jo();me();Yo();Qo();dt();Ge();ae();Q();oa.default.extend(oy.default);xt=A("base-worker"),{GET_BROWSER_TIMEOUT_MSG:sy,TEST_START_TIMEOUT_MSG:ny,TEST_COMPLETE_TIMEOUT_MSG:ra,TEST_REACHED_CUSTOM_TIMEOUT_MSG:Yu}=Pe,{SETUP_TIMEOUT:jr,NETWORK_ERROR:FE,GRID_ERROR:Qu,BROWSER_CLOSED:UE,SELENIUM_ERROR:Qt,UNKNOWN_ERROR:BE,MOBILE_SESSION_ERROR:sa}=Yr;$E=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Wt=class{constructor(e,t,r,n,i,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new ce;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await Vf(e,t.executionId,this.options,this.id,t.testResultId);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Z.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Zs(!0)}async getBrowserOnce(e,t,r,n){throw new Zs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),xt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!et({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:he.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=ts(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:he.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=O.flags.increaseTDCRequestTimeout.isEnabled(),r=Er(O.flags.appiumConnectionRequestTimeout.getValue(),(0,na.default)("2m")),n=Er(O.flags.appiumConnectionRetryCount.getValue(),1),i=r*n;return e===N.BROWSERSTACK||t&&e===N.TESTIM_TDC?i+(0,na.default)("10m"):i+(0,na.default)("1m")}getSessionTimeout(){if(ir(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,ia.default)(async()=>{let n=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Pe.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,ia.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await le(gg(o,a,this.id),this.options.getBrowserTimeout,Pe.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof sr?xt.info("could not get grid slot due to concurrency issue",r):xt.error("error getting grid slot",{error:e,...r}),await ie(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let c=this.options.getBrowserRetries-o;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,ia.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await Gf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=l,M("before getBrowserOnce");let f=await le(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Pe.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Z.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:l,id:this.options.gridData.gridId},h=this.options.mode===J.APPIUM?"device":"browser";throw xt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,r,++l),m.onDone(),!(u instanceof Lt)&&this.options.mode!==J.APPIUM&&await ie(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:c-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(o){throw await ti(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Lt,Kr].some(a=>o instanceof a)?o:o instanceof at?new vr(o,Qu):new vr(o,Qt)}return n}async runTest(e,t,r){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=ir(this.options)&&this.handleMobileTest(e);if(o)return o;M("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await Mt(),await this.runTestOnce(e,l)}finally{await ti(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var D,j;if(et(g,this.options)||ts(O,(D=this.options.gridData)==null?void 0:D.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let w=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let S=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof vr,v=S(ny),T=y&&(S(ra)||S(Yu)||v&&!e.retryOnInfraErrors),C=!!S(Yu)&&!!this.testRunTimeout,B=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||v)&&e.retryOnInfraErrors,G=T&&e.hasMoreTimeoutRetries()&&!C,E=e.hasMoreRetries()&&!b&&!T,k=!g.success&&(E||G||B);try{let V=e.retryKey;g.testRetryKey=V;let K=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,w,k,K),await this.runTestCleanup(),k){if(G&&await e.startNewTimeoutRetry(),B){xt.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:y});let q=(j=this.options.projectData)==null?void 0:j.projectId,re=e.testResultId,ge=e.testId;await aa(q,re,ge,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return E&&!B&&!G&&await e.startNewRetry(),xt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:T,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(k)}t(this.id,...r);return}catch(V){if(V instanceof rr)return;xt.error("failed to process test result",{error:V}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
214
+ Please make sure the CLI has stable access to the internet. ${jc()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:w,APP_NEVER_STARTED:S,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:v}=Qc,T=g instanceof Error?g.message:g;if(T.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),T.includes(sy)||T.includes(b))return{errorType:jr,reason:"timeout while getting device"};if(T.includes(ra)||T.includes(Yu)){if(!this.testRunTimeout)return{errorType:jr,reason:"Test timeout reached!"};let C=oa.default.duration({milliseconds:this.testRunTimeout});return{errorType:jr,reason:`Test timeout reached (timeout: ${Hi(C)})`}}return T.includes(w)||T.includes(v)?{errorType:sa,reason:"app doesn't exist on device"}:T.includes(S)?{errorType:sa,reason:"app never started, check app permission or app activity"}:T.includes(y)?{errorType:sa,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:sa,reason:T}},a=(g,y)=>{let w=this.options.mode===J.APPIUM?"device":"browser";if(!y&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:FE,reason:i()};let S=g instanceof Error?g.message:g;if(S.includes(sy))return{errorType:jr,reason:`Test couldn't get ${w}`};if(S.includes(ny))return{errorType:jr,reason:"Test couldn't be started"};if(g instanceof vr&&g.type){if(g.type===Qu)return{errorType:Qu,reason:`Test couldn't get ${w} from grid - ${g.message}`};if(g.type===Qt)return{errorType:Qt,reason:`Failed to create new session - ${g.message}`}}return S.includes(ra)?this.testRunTimeout?{errorType:jr,reason:`Test timeout reached (timeout: ${Hi(oa.default.duration({milliseconds:this.testRunTimeout}))})`}:{errorType:jr,reason:"Test timeout reached: test is too long"}:"type"in g&&g.type===UE?{errorType:Qt,reason:`Session terminated, this is often caused to connection
215
+ problems between the Testim CLI and the grid running the test. Please check your network connection.`}:"type"in g&&g.type==="KEEP_ALIVE_FAILED"?{errorType:Qt,reason:"Test terminated due to repeated keep alive failures. The browser may have become unresponsive or the test environment may be unstable."}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:Qt,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:Qt,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:Qt,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:Qt,reason:`Session could not be created, please check that the ${w} you requested is supported in your plan`}:{errorType:BE,reason:S}},c=async g=>{var v;let y=await Bc();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),xt.warn("error on run",{err:g});let w=(v=this.userData)==null?void 0:v.projectId,{errorType:S,reason:b}=this.options.mode===J.APPIUM?o(g):a(g,y);aa(w,this.testResultId,this.testId,{status:nn.COMPLETED,success:!1,reason:b,errorType:S,testRetryKey:e.retryKey,setupStepResult:{status:nn.COMPLETED,success:!1,reason:b,errorType:S}},e.remoteRunId),await n(jE(this.testId,this.testName,this.testResultId,b),g)},l=async g=>{var v;let y=this.testId,w=this.testResultId,S=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!w||!S||!b)return xt.warn("Test failed. Not enough data to recover results via API",{err:g}),c(g);try{let T=await Ur(y,w,S,b);if(xt.warn("Test failed. Got results via API",{err:g,testResult:iy.default.omit(T,$E),resultId:w}),T&&T.status===nn.COMPLETED&&!g.message.includes(ra))return await n(T);throw g}catch(T){return T!==g&&xt.error("Failed to fetch test results from server",{testId:y,resultId:w,projectId:S,branch:b,err:T}),c(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===J.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&_s.joinToRemoteStep(this.testResultId),!d&&$t.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==J.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),M("After onRunComplete"),t(this.id,...r)}catch(y){await l(y),t(this.id,...r)}finally{m||_s.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,u()}}});var cy,ay,Ls,Zu=I(()=>{"use strict";F();cy=R(require("p-retry"));F();W();Q();ay=A("window-utils"),Ls=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return ay.warn("selenium navigation failed. retrying to navigate",{err:i}),await ie(1500),r(n-1);throw!i.seleniumStack&&o&&ay.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),ie(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ie(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ie(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&!r.href.startsWith("res://ieframe.dll/http_404.htm")&&!r.href.startsWith("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")}if(!(await this.driver.executeJS(e)).value)throw new Lt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,cy.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var ep,Ds,tp=I(()=>{"use strict";W();ep=A("cookies-utils"),Ds=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw ep.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw ep.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw ep.error("failed to remove cookie",{err:t}),t}}}});var rp,ca,ly=I(()=>{"use strict";rp=R(require("p-retry")),ca=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[i,o]=await(0,rp.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,rp.default)(i,{retries:t,minTimeout:r,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function WE(s){let{loadImage:e}=await Fe("canvas"),t=Buffer.from(s,"base64");return await e(t)}async function la(s){let e=await WE(s);return{width:e.width,height:e.height}}async function uy(s,e){let{createCanvas:t,Image:r}=await Fe("canvas"),n=t(e.width,e.height),i=n.getContext("2d"),o=new r;return o.src=`data:image/png;base64,${s}`,await new Promise((a,c)=>{o.onload=()=>a(),o.onerror=c}),i.drawImage(o,e.left,e.top,e.width,e.height,0,0,e.width,e.height),n.toDataURL("image/png")}async function py(s,e){let t="image/png",{createCanvas:r,Image:n}=await Fe("canvas"),i=r(s.width,s.height),o=i.getContext("2d");for(let c of e){let l=c.image.match(/^data:([^;]*);base64,(.*)$/),d=l[1],m=l[2],u=new n;u.src=`data:${d};base64,${m}`,await new Promise((f,h)=>{u.onload=()=>f(),u.onerror=h}),o.drawImage(u,c.position.left,c.position.top,c.size.width,c.size.height)}return i.toDataURL(t)}var sp=I(()=>{"use strict";ws()});async function dy(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let i=s.offset||{top:0,left:0};if(i.top*=r,i.left*=r,!s.elementRect)return VE.warn("missing elementRect",fy.omit(s,"image")),{};let{elementRect:o}=s,a=o.left*r+i.left*r,c=o.top*r+i.top*r,l=o.width*r,d=o.height*r;a<0&&(l+=a,l=Math.max(l,0),a=0),c<0&&(d+=c,d=Math.max(d,0),c=0);let{width:m,height:u}=await la(n[1]);if(a+l>m&&(l=m-a),c+d>u&&(d=u-c),d<=0||l<=0)throw new np("height or width is equal or lower than zero");return{elementImage:await uy(n[1],{left:a,top:c,width:l,height:d})}}function GE(s,e){return py(s,e)}async function HE(){}async function qE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await HE(s[i]);return{key:i,url:o}}let r=await oe(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function my(s,e){return e||=1,s||={left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var fy,VE,np,ua,gy=I(()=>{"use strict";fy=R(require("lodash"));F();sp();W();VE=A("image-capture-utils"),np=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};ua=class{constructor(e,t,r){this.windowUtils=t;this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),r=await dy(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:my(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return qE({screenImage:t.image,absoluteScreenHighlight:my(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>ie(250),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await dy({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await o(h.scrollPos,h.cropData);f.push(g)}return f}function c(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),w=f.height,S=Array.from({length:Math.ceil(h/g)},(v,T)=>({scrollX:Math.min(T*g,h-g),cropX:T*g-Math.min(T*g,h-g),cropW:g-(T*g-Math.min(T*g,h-g))})),b=Array.from({length:Math.ceil(y/w)},(v,T)=>({scrollY:Math.min(T*w,y-w),cropY:T*w-Math.min(T*w,y-w),cropH:w-(T*w-Math.min(T*w,y-w))}));return S.flatMap(v=>b.map(T=>({scrollPos:{x:v.scrollX,y:T.scrollY},cropData:{top:T.cropY,left:v.cropX,width:v.cropW,height:T.cropH}})))}async function l(u,f){let h=await t.getCurrentScrollPosition(),g=c(u,f),y=await a(g);return await t.scrollToPosition(h),GE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(d,m)}}});var hy,yy,pa,da,by=I(()=>{"use strict";hy=R(require("p-retry")),yy=R(require("semver"));F();W();Zu();ly();gy();Se();pa=A("tab-service"),da=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),pa.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=ne();function c(l){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!l.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Ls(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new ua(t,a,new ca(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=ee(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),c=n(o),l=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===c);return c===l&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=ee();if(n){let l=this.getAllTabInfos(e),d=Object.keys(l).map(m=>l[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(l=>i[l].url);if(this.exactUrlMatch(t,r,o))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,o,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){pa.error("failed to get url or title",{err:i})}}catch(n){pa.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ie(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){pa.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let i=await this.waitForTabToOpen(e);await this.addNewTab(e,i,this.pendingTabs[e]),this.addFrameHandler(i),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,hy.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=yy.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var c,l;let{tabMatcher:r,commonConstants:n}=ee();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((c=t.useCurrentTab)!=null&&c.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(l=t.tabInfo)==null?void 0:l.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var ip,ma,op=I(()=>{"use strict";ip=class{select(){return console.log(`
216
216
  internal error - cant use port selector in selenium!!!!
217
- `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},ma=new ip});var si,fa,ga=I(()=>{"use strict";tp();F();Se();si={8:"\uE008",9:"\uE004",13:"\uE007",27:"\uE00C",33:"\uE00E",34:"\uE00F",35:"\uE010",36:"\uE011",45:"\uE016",112:"\uE031",113:"\uE032",114:"\uE033",115:"\uE034",116:"\uE035",117:"\uE036",118:"\uE037",119:"\uE038",120:"\uE039",121:"\uE03A",122:"\uE03B",123:"\uE03C"},fa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=dn;this.getLinksFromUnescapeHTML=mn;this.cookieUtils=new Ns(this.driver)}get sessionPlayerInit(){return ee()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,i=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-i.x,y:e.y-i.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function wy(s){class e{constructor(r,n){this.frameManager=r;this.LocateElementPlayer=n;this._cache={}}cacheResults(r,n){this._cache[r]=n}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let n=Ty(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,i){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:c}=ee();if(c.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw zE.error(u),new Error(u)}let l=await s.switchToLocatedFrame(a),d=Ty(l.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:l.value,frameLocateResultUrl:m}}async locate(r,n,i,o,a,c){let l=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${n}`;let d=await l.locate(r,i,r.targetId);d.isVisible=!0;let m=await l.handleLocateResult(d,c,r).catch(()=>{throw new Error("")}),{locatedElement:u}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},l.addFrameDataToContext&&l.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,i,o){let a=O.flags.enableFrameSwitchOptimization.isEnabled(),l=i.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=l&&l.stepId===r.id&&l.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(w=>w.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let w=n.slice(y+1),S=0;for(let b of w)S++,this.currentFrameHandler=await this.locate(b,S,this.currentFrameHandler,i,o,r);return this.currentFrameHandler}}let u=await o.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,i,o,r);return g}}return e}var zE,KE,Ty,vy=I(()=>{"use strict";W();me();Se();Kr();zE=A("frame-locator"),KE="ELEMENT",Ty=s=>s?s[KE]||s[er]:null});var ha,ap=I(()=>{"use strict";le();ha=()=>{try{if(qd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var H,fe=I(()=>{"use strict";Se();H=class{constructor(e,t,r,n={},i=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=i;this.locateElementPlayer=o;this.exportsTest=a;this.frameId=0}get driver(){var e;return(e=this.context.project.defaults)!=null&&e.ignoreVisibilityForExisting&&!this.stepActionUtils.driver.getIgnoreVisibility()&&this.stepActionUtils.driver.setIgnoreVisibility(!0),this.stepActionUtils.driver}get sessionPlayerInit(){return ee()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(){try{return{success:!0,...await this.performAction()}}catch(e){let t=e==null?void 0:e.message,r=e==null?void 0:e.displayMessage;return{success:!1,reason:t,exception:e,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${t}`,error:r||t}}}}}});function XE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:O.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?O.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function YE(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t){let n=new Sy.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,i,o,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:d,positionUtils:m}=ee();if(XE(n,d,m,s))return s.isVisible(e.seleniumElement);if(s.getIgnoreVisibility())return{visible:!0,invisibleReason:"visibility is ignored"};if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||c.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(T){throw Vr.error("failed to execute getVisibilityCode",{err:T}),T}let{value:w}=y||{},S=w.elementVisibilityInfo||JE,[b,v]=w.elementsFromPointResults||[null,null];return d.checkElementVisibility(S,n,v,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=ee();await s.execute(r(t))}}}var Sy,Vr,JE,ni,Ey=I(()=>{"use strict";fe();W();me();Se();Sy=require("linkedom"),Vr=A("locate-step-action"),JE={opacity:1,clientRects:{}};ni=class extends H{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return YE(e)}static getFrameIdByTestimFrameId(){throw Vr.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw Vr.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw Vr.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw Vr.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw Vr.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw Vr.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Iy={};z(Iy,{scroll:()=>QE});var QE,Ry=I(()=>{"use strict";QE=function(s,e,t,r,n,i,o,a){function c(S,b){if(!b)return{success:!1};elementScrollTo(b,S.x,S.y);let v=b.scrollLeft,T=b.scrollTop;return{success:Math.abs(T-S.y)<1&&Math.abs(v-S.x)<1,actualX:v,actualY:T}}function l(S,b){if(!t)return{x:n,y:i};let v=getLocatedElement(b);if(r&&!v)return{x:S.scrollWidth,y:S.scrollHeight};if(!v)throw new Error("could not find target element");let T=v.getBoundingClientRect(),C=0,_=0,B=Math.max(window.innerHeight-(T.height+10),0),G=Math.max(window.innerWidth-(T.width+10),0);return C=a?S.scrollTop+T.top-Math.min(i,B):S.scrollTop,_=o?S.scrollLeft+T.left-Math.min(n,G):S.scrollLeft,{x:Math.round(_),y:Math.round(C)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=l(m,e),h=c(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=l(m,e),h=c(f,m));let g=h.actualX,y=h.actualY,w=getLocatedElement(e);if(t&&r&&!w)return{success:!1,expectedPosition:f};if(t){if(!w)throw new Error("could not find target to scroll to");let S=w.getBoundingClientRect();g=S.left,y=S.top}return{success:h.success,actualX:g,actualY:y}}});var ya,xy=I(()=>{"use strict";fe();ya=class extends H{getFailureString(e,t,r,n,i){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${i}, x: ${n})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${i}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${n}`),o}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:i}}=this.sessionPlayerInit,o=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),c=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:l}=await Promise.resolve().then(()=>(Ry(),Iy)),d=`
217
+ `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},ma=new ip});var si,fa,ga=I(()=>{"use strict";tp();F();Se();si={8:"\uE008",9:"\uE004",13:"\uE007",27:"\uE00C",33:"\uE00E",34:"\uE00F",35:"\uE010",36:"\uE011",45:"\uE016",112:"\uE031",113:"\uE032",114:"\uE033",115:"\uE034",116:"\uE035",117:"\uE036",118:"\uE037",119:"\uE038",120:"\uE039",121:"\uE03A",122:"\uE03B",123:"\uE03C"},fa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=pn;this.getLinksFromUnescapeHTML=dn;this.cookieUtils=new Ds(this.driver)}get sessionPlayerInit(){return ee()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,i=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-i.x,y:e.y-i.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function wy(s){class e{constructor(r,n){this.frameManager=r;this.LocateElementPlayer=n;this._cache={}}cacheResults(r,n){this._cache[r]=n}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let n=Ty(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,i){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:c}=ee();if(c.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw zE.error(u),new Error(u)}let l=await s.switchToLocatedFrame(a);if(!l.value)throw new Error("Element not found");let d=Ty(l.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:l.value,frameLocateResultUrl:m}}async locate(r,n,i,o,a,c){let l=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${n}`;let d=await l.locate(r,i,r.targetId);d.isVisible=!0;let m=await l.handleLocateResult(d,c,r).catch(()=>{throw new Error("")}),{locatedElement:u}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},l.addFrameDataToContext&&l.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,i,o){let a=O.flags.enableFrameSwitchOptimization.isEnabled(),l=i.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=l&&l.stepId===r.id&&l.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(w=>w.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let w=n.slice(y+1),S=0;for(let b of w)S++,this.currentFrameHandler=await this.locate(b,S,this.currentFrameHandler,i,o,r);return this.currentFrameHandler}}let u=await o.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,i,o,r);return g}}return e}var zE,KE,Ty,vy=I(()=>{"use strict";W();me();Se();qr();zE=A("frame-locator"),KE="ELEMENT",Ty=s=>s?s[KE]||s[er]:null});var ha,ap=I(()=>{"use strict";ue();ha=()=>{try{if(qd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var H,fe=I(()=>{"use strict";Se();H=class{constructor(e,t,r,n={},i=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=i;this.locateElementPlayer=o;this.exportsTest=a;this.frameId=0}get driver(){var e;return(e=this.context.project.defaults)!=null&&e.ignoreVisibilityForExisting&&!this.stepActionUtils.driver.getIgnoreVisibility()&&this.stepActionUtils.driver.setIgnoreVisibility(!0),this.stepActionUtils.driver}get sessionPlayerInit(){return ee()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(){try{return{success:!0,...await this.performAction()}}catch(e){let t=e==null?void 0:e.message,r=e==null?void 0:e.displayMessage;return{success:!1,reason:t,exception:e,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${t}`,error:r||t}}}}}});function XE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:O.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?O.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function YE(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);if(!t.value)throw new Error("Element not found");e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t){let n=new Sy.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,i,o,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:d,positionUtils:m}=ee();if(XE(n,d,m,s))return s.isVisible(e.seleniumElement);if(s.getIgnoreVisibility())return{visible:!0,invisibleReason:"visibility is ignored"};if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||c.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(T){throw $r.error("failed to execute getVisibilityCode",{err:T}),T}let{value:w}=y||{},S=w.elementVisibilityInfo||JE,[b,v]=w.elementsFromPointResults||[null,null];return d.checkElementVisibility(S,n,v,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=ee();await s.execute(r(t))}}}var Sy,$r,JE,ni,Ey=I(()=>{"use strict";fe();W();me();Se();Sy=require("linkedom"),$r=A("locate-step-action"),JE={opacity:1,clientRects:{}};ni=class extends H{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return YE(e)}static getFrameIdByTestimFrameId(){throw $r.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw $r.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw $r.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw $r.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw $r.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw $r.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Iy={};z(Iy,{scroll:()=>QE});var QE,Ry=I(()=>{"use strict";QE=function(s,e,t,r,n,i,o,a){function c(S,b){if(!b)return{success:!1};elementScrollTo(b,S.x,S.y);let v=b.scrollLeft,T=b.scrollTop;return{success:Math.abs(T-S.y)<1&&Math.abs(v-S.x)<1,actualX:v,actualY:T}}function l(S,b){if(!t)return{x:n,y:i};let v=getLocatedElement(b);if(r&&!v)return{x:S.scrollWidth,y:S.scrollHeight};if(!v)throw new Error("could not find target element");let T=v.getBoundingClientRect(),C=0,_=0,B=Math.max(window.innerHeight-(T.height+10),0),G=Math.max(window.innerWidth-(T.width+10),0);return C=a?S.scrollTop+T.top-Math.min(i,B):S.scrollTop,_=o?S.scrollLeft+T.left-Math.min(n,G):S.scrollLeft,{x:Math.round(_),y:Math.round(C)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=l(m,e),h=c(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=l(m,e),h=c(f,m));let g=h.actualX,y=h.actualY,w=getLocatedElement(e);if(t&&r&&!w)return{success:!1,expectedPosition:f};if(t){if(!w)throw new Error("could not find target to scroll to");let S=w.getBoundingClientRect();g=S.left,y=S.top}return{success:h.success,actualX:g,actualY:y}}});var ya,xy=I(()=>{"use strict";fe();ya=class extends H{getFailureString(e,t,r,n,i){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${i}, x: ${n})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${i}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${n}`),o}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:i}}=this.sessionPlayerInit,o=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),c=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:l}=await Promise.resolve().then(()=>(Ry(),Iy)),d=`
218
218
  const getLocatedElement = ${n.getLocatedElementCode};
219
219
  const elementScrollTo = ${c.toString()};
220
220
  const scroll = ${l.toString()};
221
221
  return scroll.apply(null, arguments)
222
- `;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var Cy,Ay=I(()=>{"use strict";Cy=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),i=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!i)throw new Error("to element not found");let o=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var Py,ky=I(()=>{"use strict";Py=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(E){e({status:"done",result:E,success:!0})}function a(E){E||={},e({status:"failed",result:E,success:!1,keep:!0})}function c(E){return E!=null&&E.toLowerCase?(E=E.toLowerCase(),E==="text"?"text/plain":E==="url"?"text/uri-list":E):E}function l(){try{return new DataTransfer}catch{return{data:{},setData(k,D){i[c(k)]=D},getData(k){return i[c(k)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(E){let k=E;for(;k&&k!==document.documentElement;){if(k.draggable)return k;k=k.parentElement}return null}function h(E,k,D){let j=k.element,{dispatchDragEventsOnClosestDraggable:V}=D;if(d.includes(E.type)&&V){if(!j&&k.lastDraggedElement)return k.lastDraggedElement;let K=f(j);if(K)return k.lastDraggedElement=K,K}return j}function g(E,k,D){function j(ge,Ke,P){return P>ge&&P<Ke}let V=E.pointerPosition||{};if(k)return{x:V.originX||0,y:V.originY||0};let K=D.getBoundingClientRect(),q=V.originX&&j(K.left,K.left+K.width,V.originX)?V.originX:K.left+K.width/2,re=V.originY&&j(K.top,K.top+K.height,V.originY)?V.originY:K.top+K.height/2;return{x:q,y:re}}function y(E,k,D){let j=(k==null?void 0:k.modifiers)||{},V=g(E,D.isDrag,D.element),K=(k==null?void 0:k.button)||0,q=E.event;return m.includes(q)?S(q,j,V.x,V.y,K):u.includes(q)?v(q,j,V.x,V.y):b(q,j,V.x,V.y,K)}function w(E,k,D){return{screenX:0,screenY:0,clientX:k,clientY:D,ctrlKey:Boolean(E.ctrl),altKey:Boolean(E.alt),shiftKey:Boolean(E.shift),metaKey:Boolean(E.meta),bubbles:!0,cancelable:!0,composed:!0}}function S(E,k,D,j,V){if(n){let q=w(k,D,j);return q.pointerType="mouse",q.isPrimary=!0,new window.PointerEvent(E,q)}let K=document.createEvent("PointerEvent");return K.initPointerEvent(E,!0,!0,document.defaultView,1,0,0,D,j,Boolean(k.ctrl),Boolean(k.alt),Boolean(k.shift),Boolean(k.meta),V,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),K}function b(E,k,D,j,V){let K=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return K.initMouseEvent(E,!0,!0,document.defaultView,1,0,0,D,j,Boolean(k.ctrl),Boolean(k.alt),Boolean(k.shift),Boolean(k.meta),V,document.body?document.body.parentNode:document.documentElement),K}function v(E,k,D,j){if(E==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let q=document.createEvent("CustomEvent");return q.initCustomEvent(E,!0,!0,null),Object.assign(q,{dataTransfer:window.TSTA.dataTransfer}),q}let V=w(k,D,j),K=new window.DragEvent(E,V);return Object.defineProperties(K,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),K}function T(E,k,D){let j=h(E,k,D);j==null||j.dispatchEvent(E)}function C(E,k){function D(){return E.event==="click"&&k.isDrag&&!k.allEventsOnSameElement}return D()}function _(E,k,D){if(D){let j=Math.min(D.timeStamp-k.timeStamp,40);setTimeout(()=>{B(E)},j)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function B(E){let k,D=E.events[E.eventIndex],j=E.events[++E.eventIndex];try{E.element=getLocatedElement(D.locatedElement),k=y(D,s,E)}catch(V){return a(`exception in get event in drag step:${V.message}`)}if(C(D,E))return _(E,D,j);if(k)try{T(k,E,D)}catch(V){return a(`exception in executeEvent in drag step:${V.message}`)}else return a(`cannot execute event ${D.event}`);_(E,D,j)}let G={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{B(G)}catch(E){a(E)}},0)}});var Oy={};z(Oy,{doClick:()=>ZE});var ZE,_y=I(()=>{"use strict";ZE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,v){var _;function T(B){function G(){return i(B).find(D=>[...D.classList||[]].includes("Select-control"))}function E(){let D=G();return D?D.querySelector("input"):null}let k=E();k==null||k.focus()}let C=(_=b.quirks)==null?void 0:_.isReactSelect;v.type==="mousedown"&&C&&T(b.element)}function n(b,v){var C;let T=(C=b.quirks)==null?void 0:C.isCKEditorFrame;v.type==="click"&&T&&document.body.focus()}function i(b){let v=[];for(;b!=null&&b.parentNode;)v.push(b),b=b.parentNode;return v}function o(b){let v={status:"done",result:b,success:!0,...S.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function c(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},T=b.getBoundingClientRect(),C=T.left+T.width/2,_=T.top+T.height/2,E=f("mousemove",v,C,_,0);b.dispatchEvent(E)}function d(b,v){function T(E,k,D){return D>E&&D<k}let C=b.pointerPosition||{},_=v.getBoundingClientRect(),B=C.originX&&T(_.left,_.left+_.width,C.originX)?C.originX:_.left+_.width/2,G=C.originY&&T(_.top,_.top+_.height,C.originY)?C.originY:_.top+_.height/2;return{x:B,y:G}}function m(b,v,T){return{screenX:0,screenY:0,clientX:v,clientY:T,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,v,T,C){if(!window.PointerEvent)return;let _=m(v,T,C);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(b,_)}function f(b,v,T,C,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,T,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),B}function h(b,v){let T=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},_=d(b,v.element),B=v.button||0,G=b.event;return T.includes(G)?u(G,C,_.x,_.y):f(G,C,_.x,_.y,B)}function g(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return h(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),r(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let S={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!S.element){a("element not found");return}c(S.element),l(S.element);try{y(S);let b=g(),v=S.quirks,T=v==null?void 0:v.isReactSelect,C=v==null?void 0:v.isCKEditorFrame;!T&&!C&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var Ly={};z(Ly,{doDragPath:()=>eI});var eI,Dy=I(()=>{"use strict";eI=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(b){e({status:"done",result:b,success:!0})}function o(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},T=b.getBoundingClientRect(),C=T.left+T.width/2,_=T.top+T.height/2,E=u("mousemove",v,C,_,0);b.dispatchEvent(E)}function l(b,v){function T(E,k,D){return D>E&&D<k}let C=b.pointerPosition||{};if(S.isDrag)return{x:C.originX||0,y:C.originY||0};let _=v.getBoundingClientRect(),B=C.originX&&T(_.left,_.left+_.width,C.originX)?C.originX:_.left+_.width/2,G=C.originY&&T(_.top,_.top+_.height,C.originY)?C.originY:_.top+_.height/2;return{x:B,y:G}}function d(b,v,T){return{screenX:0,screenY:0,clientX:v,clientY:T,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,v,T,C,_){if(r){let G=d(v,T,C);return G.pointerType="mouse",G.isPrimary=!0,new window.PointerEvent(b,G)}let B=document.createEvent("PointerEvent");return B.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,T,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),B}function u(b,v,T,C,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,T,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),B}function f(b,v){let T=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},_=l(b,v.element),B=v.button||0,G=b.event;return T.includes(G)?m(G,C,_.x,_.y,B):u(G,C,_.x,_.y,B)}function h(b,v){function T(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return T()}function g(b,v,T){try{let C=f(v.events[b],v);h(C,v)||v.element.dispatchEvent(C)}catch{}if(b+1===v.events.length)T();else{let C=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{g(b+1,v,T)},C)}}function y(b,v){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let S={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!S.element){o("element not found");return}a(S.element),c(S.element),y(S,()=>{i()})}});var ii,ba,Ny=I(()=>{"use strict";ii=R(require("lodash"));fe();Ay();me();ky();ba=class extends H{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(_y(),Oy)),Promise.resolve().then(()=>(zn(),qn))]),l=`
222
+ `;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var Cy,Ay=I(()=>{"use strict";Cy=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),i=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!i)throw new Error("to element not found");let o=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var Py,ky=I(()=>{"use strict";Py=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(E){e({status:"done",result:E,success:!0})}function a(E){E||={},e({status:"failed",result:E,success:!1,keep:!0})}function c(E){return E!=null&&E.toLowerCase?(E=E.toLowerCase(),E==="text"?"text/plain":E==="url"?"text/uri-list":E):E}function l(){try{return new DataTransfer}catch{return{data:{},setData(k,D){i[c(k)]=D},getData(k){return i[c(k)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(E){let k=E;for(;k&&k!==document.documentElement;){if(k.draggable)return k;k=k.parentElement}return null}function h(E,k,D){let j=k.element,{dispatchDragEventsOnClosestDraggable:V}=D;if(d.includes(E.type)&&V){if(!j&&k.lastDraggedElement)return k.lastDraggedElement;let K=f(j);if(K)return k.lastDraggedElement=K,K}return j}function g(E,k,D){function j(ge,ze,P){return P>ge&&P<ze}let V=E.pointerPosition||{};if(k)return{x:V.originX||0,y:V.originY||0};let K=D.getBoundingClientRect(),q=V.originX&&j(K.left,K.left+K.width,V.originX)?V.originX:K.left+K.width/2,re=V.originY&&j(K.top,K.top+K.height,V.originY)?V.originY:K.top+K.height/2;return{x:q,y:re}}function y(E,k,D){let j=(k==null?void 0:k.modifiers)||{},V=g(E,D.isDrag,D.element),K=(k==null?void 0:k.button)||0,q=E.event;return m.includes(q)?S(q,j,V.x,V.y,K):u.includes(q)?v(q,j,V.x,V.y):b(q,j,V.x,V.y,K)}function w(E,k,D){return{screenX:0,screenY:0,clientX:k,clientY:D,ctrlKey:Boolean(E.ctrl),altKey:Boolean(E.alt),shiftKey:Boolean(E.shift),metaKey:Boolean(E.meta),bubbles:!0,cancelable:!0,composed:!0}}function S(E,k,D,j,V){if(n){let q=w(k,D,j);return q.pointerType="mouse",q.isPrimary=!0,new window.PointerEvent(E,q)}let K=document.createEvent("PointerEvent");return K.initPointerEvent(E,!0,!0,document.defaultView,1,0,0,D,j,Boolean(k.ctrl),Boolean(k.alt),Boolean(k.shift),Boolean(k.meta),V,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),K}function b(E,k,D,j,V){let K=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return K.initMouseEvent(E,!0,!0,document.defaultView,1,0,0,D,j,Boolean(k.ctrl),Boolean(k.alt),Boolean(k.shift),Boolean(k.meta),V,document.body?document.body.parentNode:document.documentElement),K}function v(E,k,D,j){if(E==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let q=document.createEvent("CustomEvent");return q.initCustomEvent(E,!0,!0,null),Object.assign(q,{dataTransfer:window.TSTA.dataTransfer}),q}let V=w(k,D,j),K=new window.DragEvent(E,V);return Object.defineProperties(K,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),K}function T(E,k,D){let j=h(E,k,D);j==null||j.dispatchEvent(E)}function C(E,k){function D(){return E.event==="click"&&k.isDrag&&!k.allEventsOnSameElement}return D()}function _(E,k,D){if(D){let j=Math.min(D.timeStamp-k.timeStamp,40);setTimeout(()=>{B(E)},j)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function B(E){let k,D=E.events[E.eventIndex],j=E.events[++E.eventIndex];try{E.element=getLocatedElement(D.locatedElement),k=y(D,s,E)}catch(V){return a(`exception in get event in drag step:${V.message}`)}if(C(D,E))return _(E,D,j);if(k)try{T(k,E,D)}catch(V){return a(`exception in executeEvent in drag step:${V.message}`)}else return a(`cannot execute event ${D.event}`);_(E,D,j)}let G={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{B(G)}catch(E){a(E)}},0)}});var Oy={};z(Oy,{doClick:()=>ZE});var ZE,_y=I(()=>{"use strict";ZE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,v){var _;function T(B){function G(){return i(B).find(D=>[...D.classList||[]].includes("Select-control"))}function E(){let D=G();return D?D.querySelector("input"):null}let k=E();k==null||k.focus()}let C=(_=b.quirks)==null?void 0:_.isReactSelect;v.type==="mousedown"&&C&&T(b.element)}function n(b,v){var C;let T=(C=b.quirks)==null?void 0:C.isCKEditorFrame;v.type==="click"&&T&&document.body.focus()}function i(b){let v=[];for(;b!=null&&b.parentNode;)v.push(b),b=b.parentNode;return v}function o(b){let v={status:"done",result:b,success:!0,...S.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function c(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},T=b.getBoundingClientRect(),C=T.left+T.width/2,_=T.top+T.height/2,E=f("mousemove",v,C,_,0);b.dispatchEvent(E)}function d(b,v){function T(E,k,D){return D>E&&D<k}let C=b.pointerPosition||{},_=v.getBoundingClientRect(),B=C.originX&&T(_.left,_.left+_.width,C.originX)?C.originX:_.left+_.width/2,G=C.originY&&T(_.top,_.top+_.height,C.originY)?C.originY:_.top+_.height/2;return{x:B,y:G}}function m(b,v,T){return{screenX:0,screenY:0,clientX:v,clientY:T,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,v,T,C){if(!window.PointerEvent)return;let _=m(v,T,C);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(b,_)}function f(b,v,T,C,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,T,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),B}function h(b,v){let T=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},_=d(b,v.element),B=v.button||0,G=b.event;return T.includes(G)?u(G,C,_.x,_.y):f(G,C,_.x,_.y,B)}function g(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return h(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),r(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let S={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!S.element){a("element not found");return}c(S.element),l(S.element);try{y(S);let b=g(),v=S.quirks,T=v==null?void 0:v.isReactSelect,C=v==null?void 0:v.isCKEditorFrame;!T&&!C&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var Ly={};z(Ly,{doDragPath:()=>eI});var eI,Dy=I(()=>{"use strict";eI=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(b){e({status:"done",result:b,success:!0})}function o(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},T=b.getBoundingClientRect(),C=T.left+T.width/2,_=T.top+T.height/2,E=u("mousemove",v,C,_,0);b.dispatchEvent(E)}function l(b,v){function T(E,k,D){return D>E&&D<k}let C=b.pointerPosition||{};if(S.isDrag)return{x:C.originX||0,y:C.originY||0};let _=v.getBoundingClientRect(),B=C.originX&&T(_.left,_.left+_.width,C.originX)?C.originX:_.left+_.width/2,G=C.originY&&T(_.top,_.top+_.height,C.originY)?C.originY:_.top+_.height/2;return{x:B,y:G}}function d(b,v,T){return{screenX:0,screenY:0,clientX:v,clientY:T,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,v,T,C,_){if(r){let G=d(v,T,C);return G.pointerType="mouse",G.isPrimary=!0,new window.PointerEvent(b,G)}let B=document.createEvent("PointerEvent");return B.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,T,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),B}function u(b,v,T,C,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,T,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),B}function f(b,v){let T=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},_=l(b,v.element),B=v.button||0,G=b.event;return T.includes(G)?m(G,C,_.x,_.y,B):u(G,C,_.x,_.y,B)}function h(b,v){function T(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return T()}function g(b,v,T){try{let C=f(v.events[b],v);h(C,v)||v.element.dispatchEvent(C)}catch{}if(b+1===v.events.length)T();else{let C=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{g(b+1,v,T)},C)}}function y(b,v){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let S={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!S.element){o("element not found");return}a(S.element),c(S.element),y(S,()=>{i()})}});var ii,ba,Ny=I(()=>{"use strict";ii=R(require("lodash"));fe();Ay();me();ky();ba=class extends H{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(_y(),Oy)),Promise.resolve().then(()=>(qn(),Hn))]),l=`
223
223
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
224
224
  var dispatchFocus = ${c.toString()};
225
225
  var doClick = ${a.toString()};
226
226
  var eventData = arguments[0];
227
227
  var done = arguments[1];
228
228
  return doClick.call(null, eventData, done);
229
- `;try{return(d=(await this.driver.executeCodeAsync(l,n,o)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var c;let e=(c=this.step.events[0])==null?void 0:c.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),i=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=n?0:r.left+r.width/2-e.originX,a=i?0:r.top+r.height/2-e.originY;return{xOffset:o,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=ii.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:n}=this.step,i=e.find(l=>["mousedown","pointerdown"].includes(l.event));if(i){let l=e.indexOf(i);e.splice(l,0,this.generateEventOfType(i,"mouseover"))}let{recordPointerMoveEvents:o=!1}=this.context.project.defaults||{},a=e.find(l=>l.event==="mouseup")||o&&e.find(l=>l.event==="pointerup"),c=Number(ii.findLastIndex(e,l=>l.event==="mousemove")||o&&ii.findLastIndex(e,l=>l.event==="pointermove"));a&&c>0&&!t&&e.splice(c+1,0,this.generateEventOfType(a,"mouseover")),r&&!n&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var d,m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3;if(!((d=e.events)!=null&&d.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let i=e.events,o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(Dy(),Ly)),Promise.resolve().then(()=>(zn(),qn))]),l=`
229
+ `;try{return(d=(await this.driver.executeCodeAsync(l,n,o)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var c;let e=(c=this.step.events[0])==null?void 0:c.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),i=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=n?0:r.left+r.width/2-e.originX,a=i?0:r.top+r.height/2-e.originY;return{xOffset:o,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=ii.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:n}=this.step,i=e.find(l=>["mousedown","pointerdown"].includes(l.event));if(i){let l=e.indexOf(i);e.splice(l,0,this.generateEventOfType(i,"mouseover"))}let{recordPointerMoveEvents:o=!1}=this.context.project.defaults||{},a=e.find(l=>l.event==="mouseup")||o&&e.find(l=>l.event==="pointerup"),c=Number(ii.findLastIndex(e,l=>l.event==="mousemove")||o&&ii.findLastIndex(e,l=>l.event==="pointermove"));a&&c>0&&!t&&e.splice(c+1,0,this.generateEventOfType(a,"mouseover")),r&&!n&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var d,m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3;if(!((d=e.events)!=null&&d.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let i=e.events,o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(Dy(),Ly)),Promise.resolve().then(()=>(qn(),Hn))]),l=`
230
230
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
231
231
  var dispatchFocus = ${c.toString()};
232
232
  var doDragPath = ${a.toString()};
@@ -242,14 +242,14 @@ Please make sure the CLI has stable access to the internet. ${jc()?"(Internal: n
242
242
  var dnd = ${Cy.toString()};
243
243
  var eventData = arguments[0];
244
244
  return dnd.call(null, eventData);
245
- `,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let c=this.driver.isSafari()&&this.step.button===2,l=this.driver.isSafari()&&e.tagName==="SELECT";return l?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!l&&(!this.step.nativeEvents||c)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=i=>i.fireOnTarget||["drop","dragenter"].includes(i.event);return e.forEach(i=>Object.assign(i,{locatedElement:n(i)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var oi,My=I(()=>{"use strict";fe();oi=class extends H{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:i}}=this,o=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(o),{evaluatedText:c}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Fy,tI,Ta,Uy=I(()=>{"use strict";Fy=R(require("lodash"));fe();W();tI=A("evaluate-expression-step-action"),Ta=class extends H{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{tI.info("runner running incoming params evaluation");let i=t.incomingParams||{};Fy.isEmpty(i)&&(i=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let o=["context",...i.as.functionParameters],a=[t,...i.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,o.concat([l]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(i){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:i.toString()},success:!1}}}}});var By={};z(By,{setText:()=>rI});var rI,jy=I(()=>{"use strict";rI=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){re()},window.addEventListener("unload",window.__unloadNavigator);let i=new Set(["keydown","keyup","keypress"]),o=15;function a(P){try{if(!t)return;let L=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return P.eventData&&(L.data=P.eventData.data),L}catch{}}function c(P){try{let L=document.createEvent("TextEvent");L.data=P.eventData.data;let $=1,Y=P.eventData.locale||"en-US";return L.initTextEvent("textInput",!0,!0,window,P.eventData.data,$,Y),L}catch{}}function l(P){return a(P)||c(P)}function d(P,L,$){try{return new KeyboardEvent(P,{bubbles:!0,cancelable:!0,location:L.location||0,key:L.key||"",ctrlKey:Boolean($.ctrl),shiftKey:Boolean($.shift),altKey:Boolean($.alt),metaKey:Boolean($.meta)})}catch{}}function m(P,L,$){try{let Y=document.createEvent("KeyboardEvent");return Y.initKeyEvent(P,!0,!0,null,Boolean($.ctrl),Boolean($.alt),Boolean($.shift),Boolean($.meta),L.key||"",0),Y}catch{}}function u(P,L,$){try{let Y=document.createEvent("Events");return Y.initEvent(P,!0,!0),Object.assign(Y,{altKey:Boolean($.alt),ctrlKey:Boolean($.ctrl),metaKey:Boolean($.meta),shiftKey:Boolean($.shift),keyCode:L.key||""}),Y}catch{}}function f(P,L,$){return d(P,L,$)||m(P,L,$)||u(P,L,$)}function h(P){if(!i.has(P.event))return null;let L=P.eventData,$=L.modifiers||{},Y=f(P.event,L,$);return Object.defineProperties(Y,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(Y,{_keyCode_:L.keyCode,_charCode_:L.charCode||0}),Y}function g(P){return P.event==="textInput"?l(P):h(P)}function y(P,L){return(()=>{var Y;return P.event==="textInput"&&!((Y=L.quirks)!=null&&Y.isAuth0Form)})()}function w(P,L){return P.event==="keyup"&&L.event==="keydown"?o:0}function S(P,L){let $=w(P,L);return Math.min(L.timeStamp-P.timeStamp,$)}function b(P){let L=Object.getOwnPropertyDescriptor(P,"value");if(!L)return;let $=P.value;P.value=`${$}#`,L.configurable&&delete P.value,P.value=$;let Y=document.createEvent("HTMLEvents");Y.initEvent("input",!0,!1),P.dispatchEvent(Y),Object.defineProperty(P,"value",L)}function v(P){if(j(P.element))try{if(b(P.element),t)P.element.dispatchEvent(new Event("change"));else{let L=document.createEvent("HTMLEvents");L.initEvent("change",!1,!0),P.element.dispatchEvent(L)}}catch{}}function T(P,L,$){$?setTimeout(()=>{D(P)},S(L,$)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(P),re())}function C(P,L){return(P==="change"||P==="blur")&&L.element.tagName==="OPTION"}function _(P,L,$){return C(P.type,L)?L.element.parentElement:$.locatedElement?getLocatedElement($.locatedElement):L.element}function B(P,L){let $=P.firstChild,Y;for(;$;){if($.nodeType===3){if(L.offset--<=0)return $}else if($.nodeType===1&&(Y=B($,L),Y))return Y;$=$.nextSibling}return null}function G(P,L){if(!(!P||!L)){if(!isNaN(L.start))Object.assign(P,{selectionStart:L.start,selectionEnd:L.end});else if(!isNaN(L.nodeOffset)){let $;if(P.firstChild?$=B(P,{offset:L.nodeOffset}):$=P,$){let Y=window.getSelection(),De=document.createRange();try{Y.removeAllRanges(),De.setStart($,L.textOffset),De.setEnd($,L.textOffset),Y.addRange(De)}catch{}}}}}function E(P,L){return P==="submit"&&Boolean(L.action)}function k(P,L,$){if(L.isFocusable&&L.isSelectable(P)&&P.type!=="submit")try{G(L.element,$.eventData.selection)}catch{}let Y=_(P,L,$);if(!Y)throw new Error("could not find element");E(P.type,Y)?Y.submit():Y.dispatchEvent(P)}function D(P){let L,$=P.events[P.eventIndex],Y=P.events[++P.eventIndex];try{L=g($)}catch(De){return ge(`exception in get event in text step:${De.message}`)}if(y($,P))return T(P,$,Y);if(L)try{k(L,P,$)}catch(De){return ge(`exception in executeEvent in text step:${De.message}`)}else if(P.noEventExecuter)P.noEventExecuter(P,$);else return ge(`cannot execute event ${$.event}`);T(P,$,Y)}function j(P){let L=P.tagName;return L==="INPUT"||L==="TEXTAREA"}function V(P){return P.getAttribute?Boolean(P.getAttribute("contenteditable")==="true"):!1}function K(P,L){if(j(P.element)){P.element.value=L.eventData.text;let $=document.createEvent("Event");$.initEvent("input",!0,!1),P.element.dispatchEvent($)}else P.isContentEditable&&(P.element.innerHTML=L.eventData.text)}function q(){var L;let P=document.activeElement;for(;(L=P.shadowRoot)!=null&&L.activeElement;)P=P.shadowRoot.activeElement;return P}function re(P){let L={status:"done",result:P,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(L)}function ge(P){P||="";let L={status:"failed",result:P,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(L)}try{let P=j(n.element);n.isContentEditable=V(n.element),!P&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=P||n.isContentEditable,n.isSelectable=L=>L.type!=="keyup",n.noEventExecuter=K}catch(P){ge(`exception in set text step:${P.message}`);return}let Ke=q();dispatchFocus(s.elementToFocusLocatedElement,Ke),D(n)}});var wa,$y=I(()=>{"use strict";fe();F();wa=class extends H{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Fe(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:i}=this,o=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:c}=i.codeSnippets;if(o.isDraftEditor&&c)return this.driver.executeJS(c(o.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let l={eventType:t,events:e,quirks:r,locatedElement:o.locatedElement,isRoot:o.isRoot,elementToFocusLocatedElement:o.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(jy(),By)),Promise.resolve().then(()=>(zn(),qn))]),u=`
245
+ `,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(m)}return this.dragPathJs()}let c=this.driver.isSafari()&&this.step.button===2,l=this.driver.isSafari()&&e.tagName==="SELECT";return l?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!l&&(!this.step.nativeEvents||c)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=i=>i.fireOnTarget||["drop","dragenter"].includes(i.event);return e.forEach(i=>Object.assign(i,{locatedElement:n(i)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var oi,My=I(()=>{"use strict";fe();oi=class extends H{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:i}}=this,o=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(o),{evaluatedText:c}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Fy,tI,Ta,Uy=I(()=>{"use strict";Fy=R(require("lodash"));fe();W();tI=A("evaluate-expression-step-action"),Ta=class extends H{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{tI.info("runner running incoming params evaluation");let i=t.incomingParams||{};Fy.isEmpty(i)&&(i=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let o=["context",...i.as.functionParameters],a=[t,...i.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,o.concat([l]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(i){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:i.toString()},success:!1}}}}});var By={};z(By,{setText:()=>rI});var rI,jy=I(()=>{"use strict";rI=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){re()},window.addEventListener("unload",window.__unloadNavigator);let i=new Set(["keydown","keyup","keypress"]),o=15;function a(P){try{if(!t)return;let L=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return P.eventData&&(L.data=P.eventData.data),L}catch{}}function c(P){try{let L=document.createEvent("TextEvent");L.data=P.eventData.data;let $=1,Y=P.eventData.locale||"en-US";return L.initTextEvent("textInput",!0,!0,window,P.eventData.data,$,Y),L}catch{}}function l(P){return a(P)||c(P)}function d(P,L,$){try{return new KeyboardEvent(P,{bubbles:!0,cancelable:!0,location:L.location||0,key:L.key||"",ctrlKey:Boolean($.ctrl),shiftKey:Boolean($.shift),altKey:Boolean($.alt),metaKey:Boolean($.meta)})}catch{}}function m(P,L,$){try{let Y=document.createEvent("KeyboardEvent");return Y.initKeyEvent(P,!0,!0,null,Boolean($.ctrl),Boolean($.alt),Boolean($.shift),Boolean($.meta),L.key||"",0),Y}catch{}}function u(P,L,$){try{let Y=document.createEvent("Events");return Y.initEvent(P,!0,!0),Object.assign(Y,{altKey:Boolean($.alt),ctrlKey:Boolean($.ctrl),metaKey:Boolean($.meta),shiftKey:Boolean($.shift),keyCode:L.key||""}),Y}catch{}}function f(P,L,$){return d(P,L,$)||m(P,L,$)||u(P,L,$)}function h(P){if(!i.has(P.event))return null;let L=P.eventData,$=L.modifiers||{},Y=f(P.event,L,$);return Object.defineProperties(Y,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(Y,{_keyCode_:L.keyCode,_charCode_:L.charCode||0}),Y}function g(P){return P.event==="textInput"?l(P):h(P)}function y(P,L){return(()=>{var Y;return P.event==="textInput"&&!((Y=L.quirks)!=null&&Y.isAuth0Form)})()}function w(P,L){return P.event==="keyup"&&L.event==="keydown"?o:0}function S(P,L){let $=w(P,L);return Math.min(L.timeStamp-P.timeStamp,$)}function b(P){let L=Object.getOwnPropertyDescriptor(P,"value");if(!L)return;let $=P.value;P.value=`${$}#`,L.configurable&&delete P.value,P.value=$;let Y=document.createEvent("HTMLEvents");Y.initEvent("input",!0,!1),P.dispatchEvent(Y),Object.defineProperty(P,"value",L)}function v(P){if(j(P.element))try{if(b(P.element),t)P.element.dispatchEvent(new Event("change"));else{let L=document.createEvent("HTMLEvents");L.initEvent("change",!1,!0),P.element.dispatchEvent(L)}}catch{}}function T(P,L,$){$?setTimeout(()=>{D(P)},S(L,$)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(P),re())}function C(P,L){return(P==="change"||P==="blur")&&L.element.tagName==="OPTION"}function _(P,L,$){return C(P.type,L)?L.element.parentElement:$.locatedElement?getLocatedElement($.locatedElement):L.element}function B(P,L){let $=P.firstChild,Y;for(;$;){if($.nodeType===3){if(L.offset--<=0)return $}else if($.nodeType===1&&(Y=B($,L),Y))return Y;$=$.nextSibling}return null}function G(P,L){if(!(!P||!L)){if(!isNaN(L.start))Object.assign(P,{selectionStart:L.start,selectionEnd:L.end});else if(!isNaN(L.nodeOffset)){let $;if(P.firstChild?$=B(P,{offset:L.nodeOffset}):$=P,$){let Y=window.getSelection(),De=document.createRange();try{Y.removeAllRanges(),De.setStart($,L.textOffset),De.setEnd($,L.textOffset),Y.addRange(De)}catch{}}}}}function E(P,L){return P==="submit"&&Boolean(L.action)}function k(P,L,$){if(L.isFocusable&&L.isSelectable(P)&&P.type!=="submit")try{G(L.element,$.eventData.selection)}catch{}let Y=_(P,L,$);if(!Y)throw new Error("could not find element");E(P.type,Y)?Y.submit():Y.dispatchEvent(P)}function D(P){let L,$=P.events[P.eventIndex],Y=P.events[++P.eventIndex];try{L=g($)}catch(De){return ge(`exception in get event in text step:${De.message}`)}if(y($,P))return T(P,$,Y);if(L)try{k(L,P,$)}catch(De){return ge(`exception in executeEvent in text step:${De.message}`)}else if(P.noEventExecuter)P.noEventExecuter(P,$);else return ge(`cannot execute event ${$.event}`);T(P,$,Y)}function j(P){let L=P.tagName;return L==="INPUT"||L==="TEXTAREA"}function V(P){return P.getAttribute?Boolean(P.getAttribute("contenteditable")==="true"):!1}function K(P,L){if(j(P.element)){P.element.value=L.eventData.text;let $=document.createEvent("Event");$.initEvent("input",!0,!1),P.element.dispatchEvent($)}else P.isContentEditable&&(P.element.innerHTML=L.eventData.text)}function q(){var L;let P=document.activeElement;for(;(L=P.shadowRoot)!=null&&L.activeElement;)P=P.shadowRoot.activeElement;return P}function re(P){let L={status:"done",result:P,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(L)}function ge(P){P||="";let L={status:"failed",result:P,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(L)}try{let P=j(n.element);n.isContentEditable=V(n.element),!P&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=P||n.isContentEditable,n.isSelectable=L=>L.type!=="keyup",n.noEventExecuter=K}catch(P){ge(`exception in set text step:${P.message}`);return}let ze=q();dispatchFocus(s.elementToFocusLocatedElement,ze),D(n)}});var wa,$y=I(()=>{"use strict";fe();F();wa=class extends H{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Be(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:i}=this,o=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:c}=i.codeSnippets;if(o.isDraftEditor&&c)return this.driver.executeJS(c(o.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let l={eventType:t,events:e,quirks:r,locatedElement:o.locatedElement,isRoot:o.isRoot,elementToFocusLocatedElement:o.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(jy(),By)),Promise.resolve().then(()=>(qn(),Hn))]),u=`
246
246
  var getLocatedElement = ${i.codeSnippets.getLocatedElementCode};
247
247
  var dispatchFocus = ${m};
248
248
  var setText = ${d.toString()};
249
249
  var eventData = arguments[0];
250
250
  var done = arguments[1];
251
251
  return setText.call(null, eventData, done);
252
- `,f=await this.driver.executeCodeAsync(u,a,l);return{success:Boolean((h=f.value)==null?void 0:h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Fe(t.seleniumElement),e[r]),r<e.length-1&&await ie(this.step.delayBetweenChars||0)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Fe(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var Wy={};z(Wy,{runCode:()=>sI});var sI,Vy=I(()=>{"use strict";sI=function(s,e){var d;function t(m,u){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let w={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(w))}catch(y){let w=y.message.toLowerCase().includes("quota"),S=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||w||S){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let T={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(T)),w||S)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let i={},o={},a={},c=s.functionParams,l=s.transactionId;try{let m=r(s);m.push(i,o,a);let u=((d=s.function)==null?void 0:d.params)||c,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(l,{type:"promise"}),h.then(g=>{t(l,{status:"done",success:!0,result:{resultValue:g,exports:i,exportsTest:o,exportsGlobal:a}})},g=>{t(l,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:i,exportsTest:o,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:h,exports:i,exportsTest:o,exportsGlobal:a}})}catch(m){t(l,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:i,exportsTest:o,exportsGlobal:a}})}}});var va,ai,gr,Sa=I(()=>{"use strict";va=R(require("lodash"));F();fe();W();me();ai=A("base-js-step-action"),gr=class extends H{isExceedingMaxResultSize(t,r){var n;try{let i=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,o=O.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>o;return i?a:(a&&ai.warn(`js result size exceeded ${o}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let n=`data-testim-${r}`;try{return window.sessionStorage.getItem(n)}catch(i){if(i.message.includes("sessionStorage")||i.message.includes("The operation is insecure")){let o=document.head.querySelector("#testim-storage-backup");return o?o.getAttribute(n):"{}"}throw i}},t)}constructJSFunParams(t){let r=t.incomingParams,n=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],i=[t.context,...r.as.functionArguments];return n.push(t.code),i.forEach(o=>{va.isObject(o)&&qi(o,"seleniumElement",va.isEqual)}),{function:{params:n,args:i},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:n,step:{id:i=""}}=this,o=r.config.retryTimeout,a=r.data.timeToPlayStep-o,c=async()=>{let l;try{l=await this.executeGetStatus(t)}catch(u){ai.warn("failed to get js status",{err:u}),l={value:'{ "status": "exception" }'}}let d;try{d=JSON.parse((l==null?void 0:l.value)||"{}")}catch{ai.warn("non object value",{selRes:l}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===i);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-o<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=o,await ie(o),c()):{success:!0})};return c()}async executeInAut(t){let r=O.flags.experimentalPreCodeCompilation.isEnabled(),n=O.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(t),o=i.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=i.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
252
+ `,f=await this.driver.executeCodeAsync(u,a,l);return{success:Boolean((h=f.value)==null?void 0:h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Be(t.seleniumElement),e[r]),r<e.length-1&&await ie(this.step.delayBetweenChars||0)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Be(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var Wy={};z(Wy,{runCode:()=>sI});var sI,Vy=I(()=>{"use strict";sI=function(s,e){var d;function t(m,u){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let w={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(w))}catch(y){let w=y.message.toLowerCase().includes("quota"),S=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||w||S){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let T={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(T)),w||S)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let i={},o={},a={},c=s.functionParams,l=s.transactionId;try{let m=r(s);m.push(i,o,a);let u=((d=s.function)==null?void 0:d.params)||c,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(l,{type:"promise"}),h.then(g=>{t(l,{status:"done",success:!0,result:{resultValue:g,exports:i,exportsTest:o,exportsGlobal:a}})},g=>{t(l,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:i,exportsTest:o,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:h,exports:i,exportsTest:o,exportsGlobal:a}})}catch(m){t(l,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:i,exportsTest:o,exportsGlobal:a}})}}});var va,ai,fr,Sa=I(()=>{"use strict";va=R(require("lodash"));F();fe();W();me();ai=A("base-js-step-action"),fr=class extends H{isExceedingMaxResultSize(t,r){var n;try{let i=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,o=O.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>o;return i?a:(a&&ai.warn(`js result size exceeded ${o}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let n=`data-testim-${r}`;try{return window.sessionStorage.getItem(n)}catch(i){if(i.message.includes("sessionStorage")||i.message.includes("The operation is insecure")){let o=document.head.querySelector("#testim-storage-backup");return o?o.getAttribute(n):"{}"}throw i}},t)}constructJSFunParams(t){let r=t.incomingParams,n=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],i=[t.context,...r.as.functionArguments];return n.push(t.code),i.forEach(o=>{va.isObject(o)&&qi(o,"seleniumElement",va.isEqual)}),{function:{params:n,args:i},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:n,step:{id:i=""}}=this,o=r.config.retryTimeout,a=r.data.timeToPlayStep-o,c=async()=>{let l;try{l=await this.executeGetStatus(t)}catch(u){ai.warn("failed to get js status",{err:u}),l={value:'{ "status": "exception" }'}}let d;try{d=JSON.parse((l==null?void 0:l.value)||"{}")}catch{ai.warn("non object value",{selRes:l}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===i);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-o<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=o,await ie(o),c()):{success:!0})};return c()}async executeInAut(t){let r=O.flags.experimentalPreCodeCompilation.isEnabled(),n=O.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(t),o=i.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=i.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
253
253
  ${t.code}
254
254
  };`:`function(${m.join(",")}) {
255
255
  ${t.code}
@@ -259,7 +259,7 @@ Please make sure the CLI has stable access to the internet. ${jc()?"(Internal: n
259
259
  var eventData = arguments[0];
260
260
  var funcToRun = ${a};
261
261
  return runCode.call(null, eventData, funcToRun);
262
- `;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:c}=t;i.exports&&(n.data.exports=i.exports);let l={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...l,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...l,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...l,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...c&&{navigateToDifferentDomain:c}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(ai.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),"stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:ai.warn("stepResultId is not present in context",{step:t,context:r}),`${r.testResultId}:${n}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),i={transactionId:this.getTransactionId(t,r),id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(i);let o=await this.checkStatus(i.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var Zt,Gy=I(()=>{"use strict";Sa();Zt=class extends gr{isFailedResult(e){return e===!1}}});var Ms,Hy=I(()=>{"use strict";Sa();Ms=class extends gr{isFailedResult(e){return!e}}});var Ea,qy=I(()=>{"use strict";fe();F();ga();Ea=class extends H{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Fe(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(si[t]),this.setWithValueApi(e)}}});var Ia,zy=I(()=>{"use strict";fe();ga();Ia=class extends H{async performAction(){var i,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((i=this.step.keys)!=null&&i.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(si[n])t.push(si[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var Ky={};z(Ky,{selectOption:()=>nI});function nI(s,e){function t(r,n){let i=Element.prototype.matches,o=i&&isNativeFunction(i)?i:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(o=>{let a=document.createEvent("HTMLEvents");return a.initEvent(o,!0,!1),a}).forEach(o=>{if(e){n.dispatchEvent(o);return}r.dispatchEvent(o)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var Jy=I(()=>{"use strict"});var Ra,Xy=I(()=>{"use strict";fe();F();me();Ra=class extends H{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,i=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&i>=13&&!a)try{return await this.driver.elementIdClick(Fe(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:c}=await Promise.resolve().then(()=>(Jy(),Ky)),l=O.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
262
+ `;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:c}=t;i.exports&&(n.data.exports=i.exports);let l={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...l,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...l,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...l,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...c&&{navigateToDifferentDomain:c}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(ai.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),"stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:ai.warn("stepResultId is not present in context",{step:t,context:r}),`${r.testResultId}:${n}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),i={transactionId:this.getTransactionId(t,r),id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(i);let o=await this.checkStatus(i.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var Zt,Gy=I(()=>{"use strict";Sa();Zt=class extends fr{isFailedResult(e){return e===!1}}});var Ns,Hy=I(()=>{"use strict";Sa();Ns=class extends fr{isFailedResult(e){return!e}}});var Ea,qy=I(()=>{"use strict";fe();F();ga();Ea=class extends H{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Be(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(si[t]),this.setWithValueApi(e)}}});var Ia,zy=I(()=>{"use strict";fe();ga();Ia=class extends H{async performAction(){var i,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((i=this.step.keys)!=null&&i.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(si[n])t.push(si[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var Ky={};z(Ky,{selectOption:()=>nI});function nI(s,e){function t(r,n){let i=Element.prototype.matches,o=i&&isNativeFunction(i)?i:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(o=>{let a=document.createEvent("HTMLEvents");return a.initEvent(o,!0,!1),a}).forEach(o=>{if(e){n.dispatchEvent(o);return}r.dispatchEvent(o)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var Jy=I(()=>{"use strict"});var Ra,Xy=I(()=>{"use strict";fe();F();me();Ra=class extends H{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,i=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&i>=13&&!a)try{return await this.driver.elementIdClick(Be(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:c}=await Promise.resolve().then(()=>(Jy(),Ky)),l=O.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
263
263
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
264
264
  const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
265
265
  const selectOption = ${c.toString()};
@@ -317,7 +317,7 @@ Please make sure the CLI has stable access to the internet. ${jc()?"(Internal: n
317
317
  input.removeAttribute("disabled");
318
318
  input.focus();
319
319
  }
320
- }`}async function uI(s,e){let t=null;try{t=(await Uc(s)).body}catch(n){if(lI.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let r=`${ib.tmpdir()}/${e}`;return await ob.promises.writeFile(r,t),r}function pI(s){return oe(s,e=>uI(e.url,e.name))}function dI(s,e){return e(s)}async function cb(s,e){let t=await pI(s),r=await oe(t,n=>dI(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var ib,ob,lI,lb=I(()=>{"use strict";ib=R(require("os"));qe();ob=require("fs");F();W();lI=A("input-file-utils")});function fI(){return`async function downloadAndUpload(locatedElement, fileUrls) {
320
+ }`}async function uI(s,e){let t=null;try{t=(await Uc(s)).body}catch(n){if(lI.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let r=`${ib.tmpdir()}/${e}`;return await ob.promises.writeFile(r,t),r}function pI(s){return oe(s,e=>uI(e.url,e.name))}function dI(s,e){return e(s)}async function cb(s,e){let t=await pI(s),r=await oe(t,n=>dI(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var ib,ob,lI,lb=I(()=>{"use strict";ib=R(require("os"));Ge();ob=require("fs");F();W();lI=A("input-file-utils")});function fI(){return`async function downloadAndUpload(locatedElement, fileUrls) {
321
321
  const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
322
322
  const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
323
323
  const attachTo = document.body || document.documentElement;
@@ -398,27 +398,27 @@ Please make sure the CLI has stable access to the internet. ${jc()?"(Internal: n
398
398
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
399
399
  var getVisibleElement = ${ab(r)};
400
400
  return getVisibleElement.apply(null, arguments);
401
- `;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 ka.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.",c="element not interactable",l="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(c)||f.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ka.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Fe(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=O.flags.overrideAzureStorageUrl.isEnabled(),n=O.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:c,driver:l}=this,d=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,c.testimServicesApi,r,ka);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 zt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),l.isSafari()||l.isFirefox()||l.isEdgeChromium()){await this.driver.executeJS(`
401
+ `;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 ka.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.",c="element not interactable",l="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(c)||f.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ka.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Be(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=O.flags.overrideAzureStorageUrl.isEnabled(),n=O.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:c,driver:l}=this,d=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,c.testimServicesApi,r,ka);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 Kt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),l.isSafari()||l.isFirefox()||l.isEdgeChromium()){await this.driver.executeJS(`
402
402
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
403
403
  const downloadAndUploadFile = ${fI()};
404
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await cb(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var _a,La,pb=I(()=>{"use strict";_a=require("url");fe();La=class extends H{async updateBaseUrl(e){let t=new _a.URL(e),r=new _a.URL(this.context.recordedBaseUrl),n=new _a.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 Da,db=I(()=>{"use strict";fe();F();Da=class extends H{async performAction(){await ie(this.step.durationMS||0)}}});var Na,mb=I(()=>{"use strict";fe();Na=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var ci,fb=I(()=>{"use strict";fe();ci=class extends H{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 Ma,gb=I(()=>{"use strict";fe();Ma=class extends H{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 hb,cp,lp,yb=I(()=>{"use strict";hb=R(require("@applitools/spec-driver-webdriverio"));Pi();Se();cp=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=Wd["@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:hb.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=ee(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},lp=new cp});var bb,up,li,Tb=I(()=>{"use strict";bb=R(require("lodash"));fe();W();yb();up=A("pixel-validation-step-action"),li=class extends H{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,c=await lp.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},d;try{let f=await c.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};bb.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),up.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()},up.info("Applitools SDK step executed successfully (selenium mode)",{projectId:this.context.projectId})}catch(f){up.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await lp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Fs,pp=I(()=>{"use strict";Os();Q();Sa();Fs=class extends gr{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:c,retryIndex:l,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await ks(i,o,a,m,c,l,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ue?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var hr,wb=I(()=>{"use strict";pp();hr=class extends Fs{isFailedResult(e){return e===!1}}});var Fa,vb=I(()=>{"use strict";pp();Fa=class extends Fs{isFailedResult(e){return!e}}});var Ua,Sb=I(()=>{"use strict";Os();fe();Q();Ua=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await Ps(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Nt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ue?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Gr,Eb=I(()=>{"use strict";fe();Gr=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var we,Ib=I(()=>{"use strict";fe();we=class extends H{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 Ba,Rb=I(()=>{"use strict";fe();Ba=class extends H{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 ja,xb=I(()=>{"use strict";fe();ja=class extends H{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 gI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function $a(s,e){gI(hI,e),e.registerLocateStepActionUtils(ni.getUtils(s))}var hI,dp=I(()=>{"use strict";Ey();xy();Ny();My();Uy();$y();Gy();Hy();qy();zy();Xy();Yy();Qy();tb();nb();ub();pb();db();mb();fb();gb();Tb();wb();vb();Sb();Eb();Ib();Rb();xb();hI={locate:ni,scroll:ya,mouse:ba,submit:xa,text:wa,"special-key":Ea,"user-code":Zt,"validation-code-step":Zt,"wait-for-code-step":Zt,"action-code-step":Zt,"condition-step":Ms,"skip-code-step":Ms,"element-code-step":Ms,"evaluate-expression":Ta,"text-validation":oi,"wait-for-text-validation":oi,"select-option":Ra,"drop-file":Pa,"input-file":Oa,hover:Ca,navigation:La,wheel:Aa,sleep:Da,refresh:Na,"keyboard-shortcut-step":Ia,"api-validation":ci,"api-action":ci,"api-code-step":Zt,"extract-text":Ma,"simple-ui-verification":li,"wait-for-simple-ui-verification":li,"cli-validation-download-file":Gr,"cli-wait-for-download-file":Gr,"network-validation-step":Gr,"cli-validation-code-step":hr,"cli-wait-for-code-step":hr,"cli-action-code-step":hr,"cli-api-code-step":hr,"cli-condition-step":Fa,"node-package":Ua,"email-code-step":Zt,"cli-email-code-step":hr,"sfdc-internal-test-step":ja,"sfdc-recorded-step":Ba,"sfdc-step-login":we,"sfdc-step-loginas":we,"sfdc-step-logout":we,"sfdc-step-sobjectcreate":we,"sfdc-step-sobjectdelete":we,"sfdc-step-findrecord":we,"sfdc-step-quickaction":we,"sfdc-step-sobjectedit":we,"sfdc-step-sobjectvalidate":we,"sfdc-step-launchapp":we,"sfdc-step-wait-for-page-load":we,"sfdc-step-closeconsoletabs":we,"sfdc-step-relatedlistaction":we,"sfdc-step-permission-validation":we,"sfdc-step-convert-lead-to-opportunity":we,"sfdc-step-quotelineeditor":we,"sfdc-document-validation":Gr,"sfdc-step-flow-screen-completion":we,"sfdc-step-sobjectverifyoptions":we}});var Cb,yI,Us,mp=I(()=>{"use strict";Cb=["simple-ui-verification","wait-for-simple-ui-verification"],yI=[...Cb,"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"],Us=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=yI.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 Cb.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 Pb={};z(Pb,{SeleniumTestPlayer:()=>ui});var Ab,bI,ui,fp=I(()=>{"use strict";F();Ab=require("@applitools/eyes-sdk-core");Kn();Q();W();tp();by();op();ga();vy();ap();Se();dp();mp();le();bI=A("SeleniumTestPlayer"),ui=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Us(ha());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=n??new Fr;let d=new fa(this.driver);this.stepActionFactory=new l(d),$a(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new da(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=wy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ns(this.driver),FrameLocator:m,portSelector:ma,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Ab.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(c.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}=ee(),t=1e3*60*2;try{await pe((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ue&&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)){bI.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=[new URL(ot||vr).hostname].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(c=>a.url.includes(c))){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 hp={};z(hp,{WorkerSelenium:()=>gp});function wI(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Wa,TI,gp,yp=I(()=>{"use strict";F();Ve();ri();W();Bt();Ko();ae();Zu();Q();fp();Se();mt();Wa=A("worker-selenium"),TI=1e9,gp=class extends $t{initPlayer(t){return new ui(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){M("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ds(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await o.init({projectData:this.options.projectData,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:l,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:J.SELENIUM,customCapabilities:t.customCapabilities}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),M("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,TI),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(l){let d=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=l.message&&l.message==="invalid argument";throw l instanceof Dt||d||m?new Dt(`Page '${c}' is not available`):(Wa.error("failed to navigate to page",{baseUrl:c,err:l,whitelistedPublicIp:po(),initializedFromCache:mo()}),l)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=ee(),{driver:o,sessionPlayer:a}=r,c=n||"runner";Z.onWaitToTestComplete(this.id),wI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===J.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let l=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(l=(await Yn(this.options))[this.testId]);let d=async()=>pe(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(f)}),this.testRunTimeout,Pe.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ue&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Wa.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&&(Wa.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(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw Wa.error("failed to run test once",{err:u}),u}}}});var kb,ze,vI,bp,At,Va=I(()=>{"use strict";kb=R(require("ora"));sp();le();qe();ye();W();ae();Se();me();ze=A("mobile-grid-service"),vI="https://tdc.tricentis-cloud.com",bp=class{constructor(){this.gridsAppIdGetter={[N.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[N.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[N.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[N.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return e.type===N.TESTIM_TDC?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===N.TESTIM_TDC?`${r||xc}/${sm}/devices`:""}getHeaders(e){return{...e.type===N.TESTIM_TDC&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...e.type===N.TESTIM_TDC&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await He({url:r,headers:n,body:i})}catch(o){throw ze.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 getTDCDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await ve(n,void 0,this.getHeaders(e));return this.extractTDCDeviceConnection(i,e.accessToken)}catch(i){throw ze.error("error while getting automation config for device",{error:i,deviceId:t}),i}}extractTDCDeviceConnection(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 e.type===N.TESTIM_TDC&&(r=await this.getTDCDeviceConnection(e,t)),r}getGridConnection(e){var r;if(e.type===N.TESTIM_TDC){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===N.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if([N.BROWSERSTACK,N.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,c,l;if(t===N.TESTIM_TDC){let d=await di({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}return t===N.BROWSERSTACK?((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName):t===N.SAUCELABS?e.testobject_device_name:e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===N.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:S}=ee();y=S(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,d,m,u,i);let w=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Lr(l,o,a,c,"RUNNING",{device:y,...w&&{remoteResultLink:w}}),ze.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:y,remoteResultLink:w,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===N.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]),c=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:c}}try{let{AppiumApi:o}=ee(),a=new o(t,r.sessionId,null,i),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),{width:d,height:m}=await la(c);return{scaleFactor:d/l.width,width:d,height:m}}catch(o){return ze.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,c,l,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:c,gridId:l})]),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===N.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ys}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===N.SAUCELABS?r.testobject_test_report_url:e.type===N.TESTIM_TVC?r.replayUrl:e.type===N.TESTIM_TDC?`${vI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await ve(`${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:c}=t,l=await this.getTmaDeviceDetails(c,e);return await Lr(a,n,i,o,"RUNNING",{device:l}),ze.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:l}),l}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?(O.flags.allowFixingAppIdStructure.isEnabled()&&(ze.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await wp({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 pi({appId:e,projectId:t});return{appUrl:`${be()}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(rm*60))+1)*60*1e3,Math.max(tm,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[N.BROWSERSTACK]:{name:"Browserstack"},[N.TESTIM_TVC]:{name:"Mobile Virtual Grid"}}[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 c=r||t.mobileApp,l=(0,kb.default)(`uploading app to ${a} please wait..`).start();try{ze.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Tp({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});return l.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw l.fail(`failed to upload app to ${a}`),ze.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 c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:c="",project:l,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!c&&e.isAppFromDevice)return n;if(c){ze.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let w=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:d});n=w.appUrl,i=w.mobileApp,e.nativeApp=i}else ze.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:m,testRunHandler:e}),y=f===N.BROWSERSTACK||f===N.TESTIM_TVC;if(g){let w=t.projectData.type,S=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:w});S&&(ze.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=g),!S&&y&&(ze.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!S&&!y&&ze.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){let{accessToken:n,user:i,host:o,key:a,type:c,apiUrl:l}=t;if(c===N.BROWSERSTACK){let d=`${Ys}/recent_apps`,m=await this.fetchWithUserAndPasswordAuth({url:d,user:i,key:a});return Array.isArray(m)?m.some(u=>u.app_url===e):!1}if(c===N.SAUCELABS){let d=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:d,user:i,key:a})).items.some(u=>u.id===e)}if(c===N.TESTIM_TDC){let d=`${l}/${Cc}/apps`;return l||(d=`${xc}/${Cc}/apps`),(await this.fetchWithTokenAuth({url:d,accessToken:n,authType:"Bearer"})).apps.some(u=>u.app_id===e)}if(c===N.TESTIM_TVC){let d=`${nm}/versions/${e}/info`,m=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:d,accessToken:m,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(u){return u.status!==404&&ze.error("error while verifying app exists on TVC",{error:u}),!1}}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await ve(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 ve(e,void 0,i)}},At=new bp});function Ob({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"&&!SI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function EI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==N.TESTIM_TDC)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 II(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 RI(s,e,t,r){let{fullReset:n,setNoReset:i,skipLoadBalancer:o}=e,c=s===N.TESTIM_TDC&&O.flags.enableBatchTDC.isEnabled(),l=O.flags.increaseTDCRequestTimeout.isEnabled();return{["tdc:capture.video"]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{["tdc:capture.network"]:!1},...o&&{["tdc:controlLock"]:!0},["tdc:retryNewSessionFailure"]:!1,["tdc:sessionTags"]:II(t),["tdc:enableBatch"]:c,...!n&&{"appium:noReset":i},...l&&{["tdc:newCommandTimeout"]:600,"appium:newCommandTimeout":600},...r}}function Ga(s){return"id"in s?s.id:s.packageName}function xI(s){return{"tdc:app.id":s}}function CI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":n},l=n==null?void 0:n.startsWith("http");n&&!l&&(c=xI(n));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":Ga(r)},...n&&c};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":Ga(r),"appium:appActivity":r.activity??".*"},...n&&c};default:throw Error(`unsupported mobile project ${s}`)}}function $s({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`]:Ga(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`]:Ga(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function _b({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a,customCapabilities:c}){let l=RI(o.type,i,n,c);return CI({projectType:s,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Sp({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 Ep({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e;return s||(n!=null&&n.deviceName?n.deviceName:i!=null&&i.deviceNameRegex?i.deviceNameRegex:t==="ios"&&r===N.BROWSERSTACK?"iPhone.*":".*")}function AI(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 Lb(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 PI(s){return Lb(s,e=>e.startsWith("browserstack."),"browserstack.")}function kI(s){return Lb(s,e=>!e.startsWith("browserstack."))}function Db(s){return!s||!Nb(s)?"2.0.0":s}function Nb(s){return s.split(".")[0]==="2"||s.includes("appium2")||["latest","stable"].includes(s)}function Mb({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),c=e==="android"&&(n.test(s)||a),l=e==="ios"&&o.test(s),d=c||l;if(t){let m=Nb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Bs(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=r.startsWith(e)?r:`${e}${r}`;t[i]=n}),t}async function OI(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c,shouldRunInEnhancedMode:l,customCapabilities:d}=s,{osVersion:m,deviceName:u}=i,f=(c==null?void 0:c.mobile)||{},{type:h}=o,g=AI(o,e),y=await di({gridId:o.gridId,projectType:e,projectId:i.project,companyId:i.company.companyId}),w=y==null?void 0:y.find(({udid:C})=>{var _;return((_=f.staticAllocation)==null?void 0:_.deviceUdid)===C}),S=(w==null?void 0:w.osVersion)??Sp({osVersion:m,mobileConfig:f}),b=(w==null?void 0:w.name)??Ep({deviceName:u,mobileConfig:f,projectType:e,gridType:h}),v=Xe(i.editorUrl,i.project,a.testId,a.testResultId,a.branch),T={device:b,os_version:S,"waldo:displayName":`${a.testName}-${a.executionId}-${a.testResultId}`,"waldo:externalUrl":v,...l&&{"waldo:automationName":"WaldoTestim"},...d};return T["waldo:options"]||(T["waldo:options"]={}),T["waldo:options"].token||(T["waldo:options"].token=g),$s({projectType:e,sessionCaps:T,nativeAppMetadata:t,appPath:r,androidActivityWait:n,shouldRunInEnhancedMode:l})}function _I({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,customCapabilities:c}){let{osVersion:l,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=Sp({osVersion:l,mobileConfig:m}),h=Ep({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),g=(0,Pt.omit)({...n.saucelabs},["automationName","platformName"]),y={...g["sauce:options"]};delete g["sauce:options"];let w={...c==null?void 0:c["sauce:options"]},S=(0,Pt.omit)(c,"sauce:options"),b=y.appiumVersion||w.appiumVersion,v=g.platformVersion||S.platformVersion||f;if(Mb({osVersion:v,projectType:s,appiumVersion:b})){let C={debug:!0,networkLogs:!0},_={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:Db(b??"stable"),deviceName:h,tags:Object.values(o)},B={"appium:platformVersion":f,"appium:deviceName":h,...Bs(g,js),...Bs(S,js),"sauce:options":{...C,..._,...(0,Pt.omit)(y,"appiumVersion"),...(0,Pt.omit)(w,"appiumVersion")}};return $s({projectType:s,sessionCaps:B,appiumPrefix:js,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let T={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:f,deviceName:h,tags:Object.values(o),name:o.testResultId,build:o.executionId,...g,...y,...S,...w};return $s({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function LI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c,customCapabilities:l}){let{osVersion:d,deviceName:m}=i,u=(c==null?void 0:c.mobile)||{},{type:f}=o,h=Sp({osVersion:d,mobileConfig:u}),g=Ep({deviceName:m,mobileConfig:u,projectType:e,gridType:f}),y=PI(i.browserstack),w=(0,Pt.omit)(kI(i.browserstack),["automationName","platformName","project","build","name"]),S={...l==null?void 0:l["bstack:options"]},b=(0,Pt.omit)(l,"bstack:options"),v=y.appiumVersion||S.appiumVersion,T=w.platformVersion||b.platformVersion||h,C=O.flags.enableAppium2BrowserStack.isEnabled(),_={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`};if(C||Mb({osVersion:T,projectType:e,isBrowserStack:!0,appiumVersion:v})){let G={..._,userName:o.user,accessKey:o.key,appiumVersion:C?"2.0.1":Db(v),debug:!0,networkLogs:!0},E={"appium:platformVersion":h,"appium:deviceName":g,...Bs(w,js),...Bs(b,js),"bstack:options":{...G,...(0,Pt.omit)(y,"appiumVersion"),...(0,Pt.omit)(S,"appiumVersion")}};return $s({projectType:e,sessionCaps:E,appiumPrefix:js,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}let B={..._,os_version:w.platformVersion||h,device:w.deviceName||g,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...w,...Bs(y,"browserstack."),...b,...Bs(S,"browserstack.")};return $s({projectType:e,sessionCaps:B,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}async function DI(s){if(N.TESTIM_TDC===s.gridInfo.type)return _b(s);if(N.TESTIM_TVC===s.gridInfo.type)return await OI(s);if(N.SAUCELABS===s.gridInfo.type)return _I(s);if(N.BROWSERSTACK===s.gridInfo.type)return LI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function NI(s,e){var l,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,c={};return n==="dynamic"&&(!i&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),i&&(c.manufacturer=i),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function Fb(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}`);Ob({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=At.getGridConnection(e),c=await DI(s);if(e.type===N.TESTIM_TDC){let y=NI(r,i==null?void 0:i.mobile);if(!(0,Pt.isEmpty)(y)){let w=Object.entries(y).map(([S,b])=>b.split(",").map(v=>v===".*"||v==="="?"":`${S}:${v}`).join(",")).join(" ").trim();c["tdc:selector"]=w}}let l=e.type===N.TESTIM_TVC?{alwaysMatch:c}:c,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,vp.default)("2m"),f=(0,vp.default)("12m"),h=Ir(O.flags.appiumConnectionRetryCount.getValue(),m),g=Ir(O.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:c,connectionRetryTimeout:g,capabilities:l,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function Ub(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;Ob({nativeAppMetadata:r,appPath:i,gridInfo:t}),EI({deviceUdid:l,gridInfo:t,testRunConfig:c});let d=l||((g=(h=c.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await At.getGridDirectConnection(t,d),f=_b({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Bb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,customCapabilities:i}=s,o={...i,dontStopAppOnReset:!0,fullReset:!1},a=$s({projectType:e,sessionCaps:o,nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete a.app,a}function jb(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 vp,Pt,js,SI,Ip=I(()=>{"use strict";vp=R(require("ms"));me();ae();Va();Pt=require("lodash");F();ye();js="appium:",SI=[N.BROWSERSTACK,N.SAUCELABS,N.TESTIM_TDC,N.TESTIM_TVC]});var Ha,Wb=I(()=>{"use strict";Ha=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 qa,Vb=I(()=>{"use strict";F();qa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=dn;this.getLinksFromUnescapeHTML=mn}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 Rp,za,Gb=I(()=>{"use strict";W();Rp=A("mobile-frame-locator-mock"),za=class{foundFrameCallback(){return Rp.info("foundFrameCallback-mock invoked"),{}}locate(){return Rp.info("locate-mock invoked"),{}}async findFrame(){return Rp.info("findFrame-mock invoked"),{}}}});var MI,qb,Hb,Ws,xp=I(()=>{"use strict";MI=R(require("webdriverio")),qb=require("@applitools/eyes-sdk-core");Wb();op();W();Vb();ap();Se();dp();Gb();mp();Hb=A("appium-test-player"),Ws=class{constructor(e,t,r,n=MI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=ee(),m=new qa(this.driver);this.stepActionFactory=new l(m),$a(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Us(ha()),this.sessionPlayer=new a(e,{tabService:new Ha,cookieUtils:void 0,FrameLocator:za,portSelector:ma,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:qb.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(c.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()),Hb.info("appium session deleted",{...i}))}catch(o){Hb.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=ee();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function FI(s){return await ve(`${s}/api/status`)}async function zb(s,e){return await ve(`${s}/api/devices/${e}/status`)}async function Kb(s){if((await FI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Jb=I(()=>{"use strict";qe()});var Xb={};z(Xb,{WorkerLocalTma:()=>kp});var Hr,Cp,Ap,Pp,kp,Yb=I(()=>{"use strict";qe();Ip();ri();F();W();Bt();xp();Se();Jb();Va();Hr=A("worker-appium"),Cp=class extends Error{},Ap=class extends Error{},Pp=class extends Error{},kp=class extends $t{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Ws(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}=ee(),{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 T;if(Z.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:c}=this.options;await Kb(o);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=c.type,f=this.options.appId;if(f){let{mobileApp:C}=await At.getMobileAppDataByAppId({appId:f,projectId:l,token:d});t.nativeApp=C}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,w=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!w)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:S,version:b},v]=await Promise.all([this.getAppStateFromDevice(o,a,w),zb(o,a)]).catch(C=>{throw this.handleDeviceNotFoundError(C),C});if(Hr.info("device status and app state",{deviceStatus:v,appInstalled:S,version:b,executionId:this.executionId,testResultId:this.testResultId}),!S&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!S&&y&&(await this.installApp(o,a,y),Hr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let C={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(T=this.options.projectData)==null?void 0:T.name}-${this.options.project}`},_=Bb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:C,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,customCapabilities:t.customCapabilities}),B={capabilities:{udid:a,..._}};Hr.info("requesting new appium session from TMA",{tmaSessionSettings:B,executionId:this.executionId,testResultId:this.testResultId});let G=await this.requestNewAppiumSessionFromTma(o,B,g);this.sessionData=G;let E=await m.attach({sessionId:G.sessionId,capabilities:_,options:{capabilities:_}});this.device=await At.updateTmaDeviceDetails(a,this.options,t),Hr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:E.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:E.capabilities})}catch(C){throw Hr.error("failed to start application",{err:C}),C}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await He({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new Pp(c):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,c=(await ve(o)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await zt(n);await nn(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new Ap(l,{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 Cp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=ee(),{sessionPlayer:o}=r,a=n||"runner";Z.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device,nativeApp:t.nativeApp},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=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(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw Hr.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw Hr.error("failed to run test once",{err:l}),l}}}});var Zb={};z(Zb,{WorkerAppium:()=>Op});var Qb,qr,Op,eT=I(()=>{"use strict";F();Ip();Qb=require("linkedom");ri();W();Bt();xp();Se();Va();ae();Ts();qr=A("worker-appium"),Op=class extends $t{initPlayer(t){return new Ws(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!==N.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Z.onGetSession(this.id,this.testName,t.runMode);let{driver:c}=n,l=await At.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,executionName:t.executionName,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch},f={projectData:this.options.projectData,projectType:o,nativeAppMetadata:m,appPath:l,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a,customCapabilities:t.customCapabilities},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await At.lockDevice(i,this.options.deviceUdid),h=await Ub(f)):h=await Fb(f),qr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:jb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await c.remote(h),this.device=await At.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),qr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw qr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=ee(),n=async()=>{try{await t.getOrientation()}catch(i){qr.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"&&hg(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){qr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===N.TESTIM_TDC?`https://${t}:${r}/v0/${n}/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}=ee(),{sessionPlayer:a}=r,c=n||"runner",l=this.options.timeout;Z.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:w,hostname:S,port:b,path:v}=await At.getTDCDeviceConnection(this.options.gridData,y);d=`${w}://${S}:${b}${v}`}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,nativeApp:t.nativeApp},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Qb.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((S,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:S,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 qr.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 pe(u(),l,Pe.TEST_REACHED_CUSTOM_TIMEOUT_MSG)}catch(y){throw qr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:test"}}});var Ka,tT=I(()=>{"use strict";F();Kn();Q();Ka=class{constructor(e){this.id=e;this.driver=new Fr}async onDone(){try{await pe(this.driver.end(),12e4)}catch(t){t instanceof ue&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function rT(){let s=await Promise.any(UI.map(async e=>{try{return await ve(e)}catch{return null}}));return s==null?void 0:s.ip}var UI,Ja,Xa=I(()=>{"use strict";qe();UI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];Ja=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var sT,Ya,nT=I(()=>{"use strict";sT=R(require("ws"));F();Xa();Ya=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=Ja({timeout:e}),r=new sT.default(this._cdpUrl,t),n=nr(o=>{r.once("open",o)}),i=nr(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([n,i]).then(()=>r),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((c,l)=>{this._cdpCallbacks.set(i,{resolve:c,reject:l})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var Za,_p,Qa,iT=I(()=>{"use strict";F();Za=R(require("chrome-launcher"));Go();nT();Fn();_p=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ya}async init(e){var h,g,y,w;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}=e,m=Vo({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((w=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:w.args)??[],...Za.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await Za.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 xr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),ws(()=>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}},Qa=class{constructor(e){this.id=e;this.sessionId=ne();this.driver=new _p(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Lp={};z(Lp,{WorkerExtension:()=>mi});function BI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function oT(s){return BI(s)?s:new Error(s)}var nt,mi,ec=I(()=>{"use strict";Ve();Q();ri();F();W();Bt();ae();tT();iT();mt();nt=A("worker-ext"),mi=class extends $t{initPlayer(){return this.options.useChromeLauncher?new Qa(this.id):new Ka(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:J.EXTENSION,useLocalChromeDriver:this.options.useLocalChromeDriver,customCapabilities:e.customCapabilities})}catch(a){throw nt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:po(),initializedFromCache:mo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Z.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var 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;M("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await pe(e.runTestUsingCDP(d.cdpTestRunner),m,Pe.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ue))throw u;return nt.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 nt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},c=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},l=async()=>{var g;if(M("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Z.onWaitToTestStart(this.id),Z.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(y){throw nt.warn("failed to run test via CDP",{err:y}),y}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let S=function(v){e.onCompletedCleanup(),nt.warn("on browser closed error detected",{err:v,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(S),m.unregisterToKeepAliveFailed(b),v.type=Zr.BROWSER_CLOSED,w.abort(v)},b=function(v){m.unregisterToClosedBrowser(S),m.unregisterToKeepAliveFailed(b),nt.warn("on keep alive failed error detected",{err:v,testResultId:r,executionId:n,testId:i}),v.type=Zr.KEEP_ALIVE_FAILED,w.abort(v)};var f=S,h=b;let y=await e.getRunTestUrl();Z.onWaitToTestStart(this.id);try{await pe(Promise.all([a(t.driver,y,u),c(u)]),this.options.testStartTimeout,Pe.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof ue))throw v;nt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let w=new AbortController;m.registerToClosedBrowser(S),m.registerToKeepAliveFailed(b);try{let v=pe(e.onCompleted(),this.testRunTimeout,Pe.TEST_COMPLETE_TIMEOUT_MSG),T=await _c(v,w.signal);m.unregisterToClosedBrowser(S),m.unregisterToKeepAliveFailed(b);try{await this.updateTestStatusOnGrid(m,Boolean(T.success),T.reason)}catch(B){nt.error("Could not update the grid about the test status",{err:B})}m.isAlive()||(nt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),T.gridIssues="could not validate grid is alive");let C=m.maxKeepAliveGap();return C>=3e4&&(nt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),T.keepAliveIssue=C),{...T,...e.seleniumPerfStats.getStats()}}catch(v){throw nt.warn("timeout wait until test completed",{err:v,testResultId:r,executionId:n,testId:i}),oT(v)}finally{m.unregisterToClosedBrowser(S),m.unregisterToKeepAliveFailed(b)}}catch(y){throw nt.warn("failed to start url",{err:y}),oT(y)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await l()}catch(d){throw nt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Np={};z(Np,{WorkerExtensionSingleBrowser:()=>Dp});var jI,$I,Dp,Mp=I(()=>{"use strict";Ve();F();W();Xu();Bt();ec();jI=A("base-worker"),$I=500,Dp=class extends mi{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await ti(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 Z.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()&&(jI.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;M("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 ie($I)}}});var Fp,tc,aT=I(()=>{"use strict";Kn();le();Ve();Ul();mt();Ou();Q();W();ae();ey();ta();Fp=A("worker-manager"),tc=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 J.SELENIUM:return(await Promise.resolve().then(()=>(yp(),hp))).WorkerSelenium;case J.APPIUM:return t?(await Promise.resolve().then(()=>(Yb(),Xb))).WorkerLocalTma:(await Promise.resolve().then(()=>(eT(),Zb))).WorkerAppium;default:return Jn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Mp(),Np))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(ec(),Lp))).WorkerExtension}else switch(r){case($r.find(n=>n===r)&&Jn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Mp(),Np))).WorkerExtensionSingleBrowser;case $r.find(n=>n===r):return(await Promise.resolve().then(()=>(ec(),Lp))).WorkerExtension;case ei.find(n=>n===r):return(await Promise.resolve().then(()=>(yp(),hp))).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 M("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,c){if(e&&e.length===0)return;let l=!1,d=0,m=(u,f)=>new Promise(h=>{var q,re,ge,Ke,P,L,$,Y;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new ea(r,n,e,i,o,t),this.combinedTestResults={};let w=((q=i.company)==null?void 0:q.ucid)||"",S=(re=i.company)==null?void 0:re.companyId,b=(ge=i.company)==null?void 0:ge.name,v=i.source||"cli",T=i.user,C=(Ke=i.company)==null?void 0:Ke.planType,_=(P=i.company)==null?void 0:P.isStartUp,B=(L=i.projectData)==null?void 0:L.name,G=($=i.projectData)==null?void 0:$.type,E=i.lightweightMode,k=(Y=i.gridData)==null?void 0:Y.type,D=(De,Lt,Ee,bc,wi,Tc)=>(d++,Zf({executionId:r,projectId:g,testId:Lt,resultId:Ee,ucid:w,companyId:S,companyName:b,projectName:B,companyPlan:C,source:v,user:T,lightweightMode:E,isStartUp:_,projectType:G,appSource:Tc,gridType:k}),t.testStartAndReport(De,r,Ee,bc,wi)),j=async(De,Lt,Ee,bc,wi,Tc)=>{var Md,Fd,Ud;d--;let it={...(E==null?void 0:E.onlyTestIdsNoSuite)&&{show:!0},...Ee.seleniumStats&&{seleniumStats:Ee.seleniumStats},...Ee.gridIssues&&{gridIssues:Ee.gridIssues},...Ee.keepAliveIssue&&{keepAliveIssue:Ee.keepAliveIssue},...i.host&&{gridHost:i.host}};if(Ee.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(Ee.seleniumPerfMarks),delete Ee.seleniumPerfMarks),i.grid||i.gridId?(it.gridName=i.grid||((Md=i.gridData)==null?void 0:Md.name),it.gridType=(Fd=i.gridData)==null?void 0:Fd.type,it.gridProvider=(Ud=i.gridData)==null?void 0:Ud.provider):i.localTmaUrl?(it.gridName="local-tma-from-options",it.gridType="local-tma"):i.useLocalChromeDriver?(it.gridName="local-chrome-driver-from-options",it.gridType="local-chrome"):i.useChromeLauncher?(it.gridName="chrome-launcher-from-options",it.gridType="local-chrome"):i.browserstack?it.gridName="browserstack-from-options":i.saucelabs&&(it.gridName="saucelabs-from-options"),await t.testEndAndReport(De,Ee,r,bc,wi,it).catch(Ew=>Fp.error("testEndAndReport threw an error",{err:Ew})),wi)return;this.combinedTestResults[Ee.resultId]=Ee,eg({executionId:r,projectId:g,testId:Lt,resultId:Ee.resultId,result:Ee,ucid:w,companyId:S,companyName:b,projectName:B,companyPlan:C,source:v,user:T,lightweightMode:E,logger:Fp,isStartUp:_,projectType:G,appSource:Tc}),c&&!Ee.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},V=(De,Lt)=>{this.combinedTestResults[Lt.resultId]=Lt,t.onTestIgnored(De,Lt.resultId),d--,(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},K=(De,Lt)=>t.onGridSlot(De,Lt);for(i.userData={loginData:{...Pr(),refreshToken:lo(),authData:Pr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:be()},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,D,j,K,V)});try{let u=await Ft(),f=await uo(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),l)throw new rr;return h}catch(u){throw Fp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var fi,cT,rc,Up,Bp,zr,jp=I(()=>{"use strict";fi=R(require("lodash"));F();W();le();ae();Ve();fs();Fl();Ul();ye();cT=require("uuid");sg();F();Bt();$g();Q();aT();me();ta();({CLI_MODE:rc}=Kt),Up=A("test-plan-runner"),Bp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return Bp._id}async runTestAllPhases(e,t,r,n,i,o,a,c){let l={},d=new tc(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,w=await d.runTests(e,c,o,a,i,n,g,y);Object.assign(l,w)},u=async()=>{let g=_i||i.parallel,y=!1;M("right before this.workerManager.runTests");let w=await d.runTests(t,c,o,a,i,n,g,y);M("right after this.workerManager.runTests"),Object.assign(l,w)},f=async()=>{let g=i.afterParallel||1,y=!1,w=await d.runTests(r,c,o,a,i,n,g,y);Object.assign(l,w)};tg({executionId:o,projectId:i.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),l}catch(g){if(Up.error("error running test plan",{err:g}),g instanceof rr)return c.markAllQueuedTests(o,he.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,w,S,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===rc.SELENIUM){let[{getSessionPlayer:v},{makeSDK:T}]=await Promise.all([Promise.resolve().then(()=>(Se(),dr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=v();await C.closeBatch(o,T);return}let g;try{if(!((b=(S=(w=i.company)==null?void 0:w.activePlan)==null?void 0:S.premiumFeatures)!=null&&b.applitools)||(g=await Gp(i.project),fi.default.isEmpty(g)||!o))return;let{runKey:v,url:T}=g,C=require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}),_=1e4;await pe(C.closeBatches({settings:{batchIds:[o],serverUrl:T,apiKey:v}}),_)}catch{}}}async runTestPlan(e,t,r,n,i,o,a,c){var b,v,T;let l=ne(),d=n.project;hm(l),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Do(m,n,o,a),f=fi.default.chain(m).map(C=>{var _;return((_=C.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(C=>C.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,d,this.startTime,i,g);M("before testListInfoPromise");let w=await y;(T=n.lightweightMode)!=null&&T.onlyTestIdsNoSuite||Z.onTestPlanStarted(w.beforeTests,w.tests,w.afterTests,i,l,c,h),M("before runTestAllPhases");let S=await this.runTestAllPhases(w.beforeTests,w.tests,w.afterTests,a,n,l,i||"All Tests",u);return M("before executionEnd"),await u.executionEnd(l),M("after executionEnd"),{results:S,executionId:l,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(de.colorString(de.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await $p(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await Wp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){Up.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return fi.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:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await oe(e.testPlanIds,async d=>{let m=await gi(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 oe(e.testPlan,async d=>{let m=await gi(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 gi(o,e.testPlan,e.testPlanIds,t,e.intersections);let c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new x(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new x(`no test to run in test plan ${e.testPlan}`)}return e.mode!==rc.APPIUM&&await Ku(e,r(l)),await oe(c,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 $f(e,d);let f=u.overrideExecutionName||d.name;return await oe(l[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Z.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let w=Object.keys(n[m]).map(T=>({executionId:T,status:zu(n[m][T])})),S=Object.keys(n[m]).map(T=>n[m][T]).reduce((T,C)=>Object.assign(T,C),{}),b=zu(S);Object.assign(i,S);let v=b?w[0].executionId:w.find(T=>!T.status).executionId;return await Vp(o,m,{success:b,executions:w,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var c;Up.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await ry(e,t);if(M("after getSuite"),!((c=r==null?void 0:r.tests[0])!=null&&c.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;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===rc.APPIUM&&(a=await pi({appId:e.appId,projectId:e.project})),await oe(r.tests,async l=>{if(a&&l.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=l[0];m.resultId=e.resultId,l=[m]}e.mode!==rc.APPIUM&&await Ku(e,l),M("right before runTestPlan");let d=await this.runTestPlan([],l,[],e,i,null,t,o);return M("right after runTestPlan"),await Z.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=Pn(),r=[];await this.reportTestRunnerStarted(e.project,e),ln(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=fi.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},zr=Bp;zr._id=(0,cT.v4)()});var ke={};z(ke,{addTestRetry:()=>yu,clearTestResult:()=>Hu,deleteCloudflareTunnel:()=>Zp,fetchLambdatestConfig:()=>wu,fixGridAppIDStructure:()=>wp,forceUpdateCloudflareTunnelRoutes:()=>Qp,getAllGrids:()=>Ml,getAppDetails:()=>pi,getApplitoolsIntegrationData:()=>Gp,getBrowserStackSessionMetaData:()=>YI,getCloudflareTunnel:()=>Yp,getCustomCapabilitiesByName:()=>td,getEditorUrl:()=>KI,getFileUrl:()=>zp,getGridSlot:()=>Nl,getHybridGridProvider:()=>Dl,getLabFeaturesByProjectId:()=>_u,getMobileDevicesFromGrid:()=>di,getRealData:()=>uu,getS3Artifact:()=>Bn,getS3ArtifactText:()=>lu,getSuiteTestList:()=>Ju,getTestPlan:()=>zI,getTestPlanTestList:()=>gi,getTestResults:()=>jr,getUsageForCurrentBillingPeriod:()=>Jp,initializeUserWithAuth:()=>Xp,isTestResultCompleted:()=>Gu,keepAliveCompanySlots:()=>au,keepAliveGrid:()=>_l,loadSfdcCredential:()=>Kp,loadTest:()=>Qn,releaseCompanySlot:()=>iu,releaseGridSlot:()=>Ll,reportExecutionFinished:()=>No,reportExecutionStarted:()=>hu,reportRunnerFinished:()=>Wp,reportRunnerStarted:()=>$p,requestCompanySlot:()=>nu,saveRemoteStep:()=>Du,saveTestPlanResult:()=>Vp,updateCompanySlot:()=>ou,updateExecutionTests:()=>gu,updateRemoteRunFailure:()=>ed,updateTestDataArtifact:()=>Mo,updateTestResult:()=>aa,updateTestStatus:()=>Lr,uploadAppToGrid:()=>Tp,uploadRunDataArtifact:()=>qu,validateUserAccessKey:()=>kl});async function Vs(){let s=await Ft();if(!s)throw new Error("Failed to get token from server");return{[Zc]:zr.id,Authorization:`Bearer ${s}`}}async function Ce({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await Vs(),o={...t,...i};return He({url:`${be()}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function HI(s,e,t,r={},n=void 0){let i=await Vs(),o={...r,...i};return await nn(`${be()}${s||""}`,e,t,o,n)}async function hi(s,e){let t=await Vs();return await Fc(`${be()}${s||""}`,e,t)}async function uT(s,e){let t=await Vs();return await sn(`${be()}${s||""}`,e,t)}async function qI(s,e){let t=await Vs();return await Mc(`${be()}${s||""}`,e||void 0,t)}async function xe(s,e,t,r){let n=await Vs();return await ve(`${be()}${s||""}`,e||void 0,n,r,t)}function Bn(s,e){return(0,te.default)(()=>xe(`/storage${s}`,null,{isBinary:!0},e),{retries:se,factor:1})}function zp(s,e){return(0,te.default)(()=>xe(`/files/fileUrl?${s}`,null,{isBinary:!0},e),{retries:se,factor:1})}function lu(s){return(0,te.default)(()=>qI(`/storage${s}`))}async function $p(s,e){return await Ce({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function Wp(s){return await uT("/test-runner",{projectId:s})}async function zI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,te.default)(()=>xe("/testPlan",{projectId:s,name:e.join(",")}),{retries:se,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function Kp({branch:s,projectId:e}){let t=await(0,te.default)(()=>xe(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:se,factor:1});return t==null?void 0:t.sfdcCredential}function Qn({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,te.default)(()=>xe(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:se,factor:1})}function Vp(s,e,t){return(0,te.default)(()=>Ce({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:se,factor:1})}function Lr(s,e,t,r,n,i,o=se){return(0,te.default)(()=>hi("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:WI,...i}),{retries:o,factor:1})}function gu(s,e,t,r,n,i,o,a){return(0,te.default)(()=>hi("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:se,factor:1})}async function hu({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(bo(),Xf));return Ce({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:c,isLocalRun:l}},retry:3})}function No(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,te.default)(()=>hi("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:se,factor:1})}async function gi(s,e,t,r,n){return(0,te.default)(()=>Ce({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:se,factor:1})}function Ju({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}){return(0,te.default)(()=>Ce({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}}),{retries:se,factor:1})}async function pi({appId:s,projectId:e}){try{let t=await(0,te.default)(()=>xe(`/mobile-app/app/${s}?projectId=${e}`),{retries:se,factor:1});return Vt.omit(t,"version")}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function Jp(s){try{return await(0,te.default)(()=>xe(`/plan/project/${s}/usage-current-billing-period`),{retries:se,factor:1})}catch(e){Wt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Gu(s,e,t){return(0,te.default)(()=>xe(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:se,factor:1})}function jr(s,e,t,r){return(0,te.default)(()=>xe(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:se,factor:1})}function _l(s,e){return Ce({url:`/grid/keep-alive?reqId=${ne()}`,body:{projectId:s,slots:e},timeout:1e4})}function Ll(s,e,t,r,n){return Ce({url:`/grid/release?reqId=${ne()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Dl(s){return Ce({url:"/grid/hybrid/provider",body:s})}function Nl(s){return(0,te.default)(()=>xe("/grid/grid-slot",{...s,reqId:ne()}),{retries:se,factor:1})}async function Xp({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d}){var m,u;try{return await(0,te.default)(()=>He({url:`${be()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d},timeout:6e4}),{retries:se,factor:1})}catch(f){if(Wt.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new x("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((u=f.code)!=null&&u.includes("ENOTFOUND"))throw new x("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",y=h.clientMessage.bgColor||"bgBlack";console.log(Hp.default[y](Hp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Wt.error("Error parsing error message from server",f)}throw f}}async function KI(){if(ot)return{editorUrl:ot};try{return await(0,te.default)(()=>xe("/system-info/editor-url"),{retries:se,onFailedAttempt:s=>{if(s.attemptNumber>=se)throw s},factor:1})}catch(s){return Wt.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Ml(s){return(0,te.default)(()=>xe("/grid",{companyId:s}),{retries:se,factor:1})}function uu(s,e,t){return(0,te.default)(()=>xe(`/real-data/${e}?${t}&projectId=${s}`),{retries:se,factor:1})}function aa(s,e,t,r,n){return(0,te.default)(()=>Ce({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:se,factor:1})}function Hu(s,e,t,r){return(0,te.default)(()=>Ce({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:se,factor:1})}function Du(s,e,t,r){return(0,te.default)(()=>Ce({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:se,factor:1})}function JI(s){return s.startsWith("/")?s:`/${s}`}function XI(s,e,t){let r=JI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function pT(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${ne()}${o||""}`,c=`${e}/${t}/${a}`,l=XI(c,GI,s),d=Buffer.from(lT.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,te.default)(()=>HI(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:se,factor:1}),l}function yu({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,te.default)(()=>Ce({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:se,factor:1})}async function Gp(s){try{return await xe(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Wt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Yp(s,e){try{return await hi("/tunnel",{companyId:s,routes:e})}catch(t){return Wt.warn("could'nt get tunnel.",{err:t}),{}}}async function Qp(s,e){try{return await Ce({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}async function Zp(s,e){try{return await uT(`/tunnel/${e}`,{companyId:s})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}function ed(s){return He({url:`${be()}/result/remoteRunFailure`,body:s})}async function di({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${VI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,te.default)(()=>xe(i,{projectId:s}),{retries:se,factor:1})}catch(o){return Wt.warn("could'nt get devices from grid.",{err:o}),null}}async function Tp({projectId:s,gridId:e,app:t,timeout:r}){return(0,te.default)(()=>Ce({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:se,factor:1})}async function wp(s){return(0,te.default)(()=>Ce({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:se,factor:1})}async function nu(s,e){return(0,te.default)(()=>Ce({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:se,factor:1})}async function iu(s,e,t){return(0,te.default)(()=>Ce({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:se,factor:1})}async function ou(s,e,t){return(0,te.default)(()=>hi("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:se,factor:1})}function au(s,e,t){return Ce({url:`/slot-management/keep-alive?reqId=${ne()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function YI(s,e){return await ve(`${Ys}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function kl(s){try{return await xe("/v2/project/validateUserAccessKey",s),!0}catch(e){return Wt.error("error validating user access key",{error:e}),!1}}async function td(s,e){let[t]=await xe("/capabilities?",{projectId:s,name:e});return t}var Hp,Vt,lT,te,qp,WI,Wt,se,VI,GI,wu,_u,qu,Mo,ye=I(()=>{"use strict";Hp=R(require("chalk")),Vt=R(require("lodash")),lT=R(require("pako"));F();le();ae();qe();mt();te=R(require("p-retry")),qp=R(require("object-hash"));Q();W();jp();WI=at(),Wt=A("testim service api"),se=3,VI="/grid",GI="test-result-artifacts";wu=async(s,e)=>(0,te.default)(()=>xe("/grid/lt/config",{companyId:s,...e&&{projectId:e}}),{retries:se,factor:1}),_u=async s=>(0,te.default)(()=>xe(`/labFeature/v2/project/${s}`),{retries:se,factor:1});qu=Vt.memoize(async(s,e,t,r)=>{if(!Vt.isEmpty(r))return await pT(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,qp.default)(r)}:${e}:${t}`),Mo=Vt.memoize(async(s,e,t,r,n)=>!r||Vt.isEmpty(r)?void 0:await pT(s,e,t,JSON.stringify((()=>{let o=Vt.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:Xc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,qp.default)(r)}:${e}:${t}`)});function sc(){return at()}var rd=I(()=>{"use strict";F()});function eR(s){J.EXTENSION!==s&&process.nextTick(()=>{try{(Se(),Je(dr)).getSessionPlayer()}catch{}})}function tR(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let n=r.color||"yellow",i=r.bgColor||"bgBlack";console.log(sd.default[i](sd.default[n](r.text)))})}function rR(s,e){let{serviceUrl:t}=s;Qs(t),pt(async()=>s,es.CACHE_FN_NAME,es.TTL,{serviceUrl:t})(),Gt.setRegion(Gg[Is(e)])}async function yi(s){var b;let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?ZI:QI,f=sc(),h=Hc(),g=await gf(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await rT()}catch(v){dT.error("failed to get public ip",v)}let w=!0;M("before initializeUserWithAuth");let S=await pt(async()=>(eR(a),w=!1,await Xp({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:y,gridId:c,grid:l,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:c,grid:l,publicIp:y})();return tR(S),rR(S.clientConfig,e),s.publicIps=[S.clientPublicIp],M("after initializeUserWithAuth"),y&&S.clientPublicIp&&S.clientPublicIp!==y&&(dT.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:S.clientPublicIp}),s.publicIps.push(y)),Nf(S.authData,{projectId:e,token:t,userAccessKey:r,publicIp:S.clientPublicIp,initializedFromCache:w}),Jf((b=S.clientConfig)==null?void 0:b.segmentKey),S}var sd,dT,QI,ZI,mT=I(()=>{"use strict";sd=R(require("chalk"));Ve();ye();Jt();mt();Xa();ae();W();me();rd();F();ds();le();Uo();kr();dT=A("initializeUserWithAuth"),QI=1e3*60*5,ZI=1e3*60*60*10});async function hT(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await co():s.chromeBinaryLocation,e=yn({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==J.EXTENSION&&await Cr(s.playerLocation,s.canary),s.mode!==J.SELENIUM&&s.mode!==J.APPIUM&&!s.ext&&await wl(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Tl(s.installCustomExtension,n)}return await e,t}async function yT(s){var o;sR.info("prepare MockNetwork",{location:s});let e=await Wc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>fT*1e6)throw new Error(`${nd} exceeded ${fT}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${nd} cannot be parsed.${nc.EOL}${a}`)}let n=new gT.default;if(!n.validate(ll,r)){let a=(o=n.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(nc.EOL);throw new Error(`${nd} is malformed.${nc.EOL}${a}`)}return r.entries}var nc,gT,fT,nd,sR,id=I(()=>{"use strict";nc=R(require("node:os"));F();zm();Tn();gT=R(require("ajv"));ae();Il();W();mT();fT=1,nd="JSON file supplied to --mock-network-pattern",sR=A("prepare runner")});function ST(s){return s.start&&gs(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function ET(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new x("Agent port is not number");let t=Fo(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var IT=I(()=>{"use strict";Vn();kr();Q()});var Gs,ld,RT=I(()=>{"use strict";Gs="SECRETS",ld={get secretsKey(){return Gs},get proxySecrets(){return new Proxy({},{get(s,e){return`${Gs}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[Gs]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(Gs):JSON.stringify(s).includes(Gs)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${Gs}\\.\\w+`,"g"));return r==null||r.map(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${r}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(n);if(l){let d=l[1];o[c]=e[d]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(n);if(l){let d=l[1];o[a]=e[d]??c}}else typeof c=="object"&&c!==null&&i(c)})};i(s)}}});var fd={};z(fd,{doLogin:()=>md,getProjectId:()=>lR,getToken:()=>uR});async function lR(){return AT("projectId")}async function uR(){return AT("token")}function CT(s,e){return Promise.race([s,ie(e).then(()=>{throw new ue("timeout")})])}async function pR(){let s=(await import("express")).default(),e=async function(){return CT(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ye(),ke)),{editorUrl:n}=await r();Po(`${n}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${ot||vr}`)}return await e}async function md({overwriteExisting:s=!0,projects:e=null}={}){let t=ud.homedir(),r=pd.join(t,".testim");if(await Te(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await CT(pR(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,c.succeed(),await xT(r,i);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=l.project.ci.token,i.projectId=l.project.id,await xT(r,i);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function xT(s,e){await dd.promises.writeFile(s,oc.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function AT(s){let e=ud.homedir(),t=pd.join(e,".testim"),r=await Te(t),n={};if(r)try{n=oc.parse((await dd.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var ud,pd,oc,dd,ac=I(()=>{"use strict";ud=R(require("os")),pd=R(require("path")),oc=R(require("yaml"));F();dd=require("fs");Q();eu();le()});var FT={};z(FT,{process:()=>wR,program:()=>p});var hd,LT,cc,DT,Ot,_e,NT,dR,Be,mR,bd,fR,gR,kT,MT,bi,yd,lc,Td,gd,kt,OT,hR,yR,p,bR,TR,_T,wR,UT=I(()=>{"use strict";hd=R(require("ms")),LT=R(require("chalk")),cc=R(require("node:fs")),DT=R(require("node:url")),Ot=R(require("lodash")),_e=R(require("node:path"));F();Vn();IT();Jt();NT=require("commander");ae();Q();Kr();F();me();RT();ta();Uo();le();vu();dR=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Be=(s,e)=>(e.push(s),e),mR=s=>(e,t)=>{if(t!==void 0)throw new x(`The ${s} flag can only be specified once.`);return e},bd=new NT.Command,fR=s=>s.split(","),gR=(s,e)=>!s||s.length===0?e:s,kT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],MT=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}bd.help(g=>g.split(`
404
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await cb(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var _a,La,pb=I(()=>{"use strict";_a=require("url");fe();La=class extends H{async updateBaseUrl(e){let t=new _a.URL(e),r=new _a.URL(this.context.recordedBaseUrl),n=new _a.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 Da,db=I(()=>{"use strict";fe();F();Da=class extends H{async performAction(){await ie(this.step.durationMS||0)}}});var Na,mb=I(()=>{"use strict";fe();Na=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var ci,fb=I(()=>{"use strict";fe();ci=class extends H{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 Ma,gb=I(()=>{"use strict";fe();Ma=class extends H{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 hb,cp,lp,yb=I(()=>{"use strict";hb=R(require("@applitools/spec-driver-webdriverio"));Pi();Se();cp=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=Wd["@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:hb.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=ee(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},lp=new cp});var bb,up,li,Tb=I(()=>{"use strict";bb=R(require("lodash"));fe();W();yb();up=A("pixel-validation-step-action"),li=class extends H{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,c=await lp.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},d;try{let f=await c.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};bb.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),up.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()},up.info("Applitools SDK step executed successfully (selenium mode)",{projectId:this.context.projectId})}catch(f){up.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await lp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ms,pp=I(()=>{"use strict";ks();Q();Sa();Ms=class extends fr{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:c,retryIndex:l,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await Ps(i,o,a,m,c,l,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof pe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var gr,wb=I(()=>{"use strict";pp();gr=class extends Ms{isFailedResult(e){return e===!1}}});var Fa,vb=I(()=>{"use strict";pp();Fa=class extends Ms{isFailedResult(e){return!e}}});var Ua,Sb=I(()=>{"use strict";ks();fe();Q();Ua=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await As(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Dt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof pe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Wr,Eb=I(()=>{"use strict";fe();Wr=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var we,Ib=I(()=>{"use strict";fe();we=class extends H{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 Ba,Rb=I(()=>{"use strict";fe();Ba=class extends H{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 ja,xb=I(()=>{"use strict";fe();ja=class extends H{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 gI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function $a(s,e){gI(hI,e),e.registerLocateStepActionUtils(ni.getUtils(s))}var hI,dp=I(()=>{"use strict";Ey();xy();Ny();My();Uy();$y();Gy();Hy();qy();zy();Xy();Yy();Qy();tb();nb();ub();pb();db();mb();fb();gb();Tb();wb();vb();Sb();Eb();Ib();Rb();xb();hI={locate:ni,scroll:ya,mouse:ba,submit:xa,text:wa,"special-key":Ea,"user-code":Zt,"validation-code-step":Zt,"wait-for-code-step":Zt,"action-code-step":Zt,"condition-step":Ns,"skip-code-step":Ns,"element-code-step":Ns,"evaluate-expression":Ta,"text-validation":oi,"wait-for-text-validation":oi,"select-option":Ra,"drop-file":Pa,"input-file":Oa,hover:Ca,navigation:La,wheel:Aa,sleep:Da,refresh:Na,"keyboard-shortcut-step":Ia,"api-validation":ci,"api-action":ci,"api-code-step":Zt,"extract-text":Ma,"simple-ui-verification":li,"wait-for-simple-ui-verification":li,"cli-validation-download-file":Wr,"cli-wait-for-download-file":Wr,"network-validation-step":Wr,"cli-validation-code-step":gr,"cli-wait-for-code-step":gr,"cli-action-code-step":gr,"cli-api-code-step":gr,"cli-condition-step":Fa,"node-package":Ua,"email-code-step":Zt,"cli-email-code-step":gr,"sfdc-internal-test-step":ja,"sfdc-recorded-step":Ba,"sfdc-step-login":we,"sfdc-step-loginas":we,"sfdc-step-logout":we,"sfdc-step-sobjectcreate":we,"sfdc-step-sobjectdelete":we,"sfdc-step-findrecord":we,"sfdc-step-quickaction":we,"sfdc-step-sobjectedit":we,"sfdc-step-sobjectvalidate":we,"sfdc-step-launchapp":we,"sfdc-step-wait-for-page-load":we,"sfdc-step-closeconsoletabs":we,"sfdc-step-relatedlistaction":we,"sfdc-step-permission-validation":we,"sfdc-step-convert-lead-to-opportunity":we,"sfdc-step-quotelineeditor":we,"sfdc-document-validation":Wr,"sfdc-step-flow-screen-completion":we,"sfdc-step-sobjectverifyoptions":we}});var Cb,yI,Fs,mp=I(()=>{"use strict";Cb=["simple-ui-verification","wait-for-simple-ui-verification"],yI=[...Cb,"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"],Fs=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=yI.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 Cb.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 Pb={};z(Pb,{SeleniumTestPlayer:()=>ui});var Ab,bI,ui,fp=I(()=>{"use strict";F();Ab=require("@applitools/eyes-sdk-core");Kn();Q();W();tp();by();op();ga();vy();ap();Se();dp();mp();ue();bI=A("SeleniumTestPlayer"),ui=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Fs(ha());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=n??new Nr;let d=new fa(this.driver);this.stepActionFactory=new l(d),$a(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new da(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=wy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ds(this.driver),FrameLocator:m,portSelector:ma,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Ab.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(c.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}=ee(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof pe&&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)){bI.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=[new URL(it||wr).hostname].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(c=>a.url.includes(c))){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 hp={};z(hp,{WorkerSelenium:()=>gp});function wI(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Wa,TI,gp,yp=I(()=>{"use strict";F();$e();ri();W();Ut();Ko();ae();Zu();Q();fp();Se();dt();Wa=A("worker-selenium"),TI=1e9,gp=class extends Wt{initPlayer(t){return new ui(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){M("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ls(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await o.init({projectData:this.options.projectData,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:l,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:J.SELENIUM,customCapabilities:t.customCapabilities}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),M("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,TI),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(l){let d=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=l.message&&l.message==="invalid argument";throw l instanceof Lt||d||m?new Lt(`Page '${c}' is not available`):(Wa.error("failed to navigate to page",{baseUrl:c,err:l,whitelistedPublicIp:po(),initializedFromCache:mo()}),l)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=ee(),{driver:o,sessionPlayer:a}=r,c=n||"runner";Z.onWaitToTestComplete(this.id),wI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===J.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let l=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(l=(await Yn(this.options))[this.testId]);let d=async()=>le(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(f)}),this.testRunTimeout,Pe.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof pe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Wa.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&&(Wa.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(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw Wa.error("failed to run test once",{err:u}),u}}}});var kb,qe,vI,bp,Ct,Va=I(()=>{"use strict";kb=R(require("ora"));sp();ue();Ge();ye();W();ae();Se();me();qe=A("mobile-grid-service"),vI="https://tdc.tricentis-cloud.com",bp=class{constructor(){this.gridsAppIdGetter={[N.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[N.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[N.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[N.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return e.type===N.TESTIM_TDC?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===N.TESTIM_TDC?`${r||xc}/${sm}/devices`:""}getHeaders(e){return{...e.type===N.TESTIM_TDC&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...e.type===N.TESTIM_TDC&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:i})}catch(o){throw qe.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 getTDCDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await ve(n,void 0,this.getHeaders(e));return this.extractTDCDeviceConnection(i,e.accessToken)}catch(i){throw qe.error("error while getting automation config for device",{error:i,deviceId:t}),i}}extractTDCDeviceConnection(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 e.type===N.TESTIM_TDC&&(r=await this.getTDCDeviceConnection(e,t)),r}getGridConnection(e){var r;if(e.type===N.TESTIM_TDC){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===N.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if([N.BROWSERSTACK,N.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,c,l;if(t===N.TESTIM_TDC){let d=await di({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}return t===N.BROWSERSTACK?((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName):t===N.SAUCELABS?e.testobject_device_name:e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===N.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:S}=ee();y=S(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,d,m,u,i);let w=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await _r(l,o,a,c,"RUNNING",{device:y,...w&&{remoteResultLink:w}}),qe.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:y,remoteResultLink:w,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===N.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]),c=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:c}}try{let{AppiumApi:o}=ee(),a=new o(t,r.sessionId,null,i),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),{width:d,height:m}=await la(c);return{scaleFactor:d/l.width,width:d,height:m}}catch(o){return qe.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,c,l,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:c,gridId:l})]),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===N.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Xs}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===N.SAUCELABS?r.testobject_test_report_url:e.type===N.TESTIM_TVC?r.replayUrl:e.type===N.TESTIM_TDC?`${vI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await ve(`${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:c}=t,l=await this.getTmaDeviceDetails(c,e);return await _r(a,n,i,o,"RUNNING",{device:l}),qe.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:l}),l}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?(O.flags.allowFixingAppIdStructure.isEnabled()&&(qe.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await wp({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 pi({appId:e,projectId:t});return{appUrl:`${be()}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(rm*60))+1)*60*1e3,Math.max(tm,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[N.BROWSERSTACK]:{name:"Browserstack"},[N.TESTIM_TVC]:{name:"Mobile Virtual Grid"}}[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 c=r||t.mobileApp,l=(0,kb.default)(`uploading app to ${a} please wait..`).start();try{qe.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Tp({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});return l.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw l.fail(`failed to upload app to ${a}`),qe.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:c="",project:l,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!c&&e.isAppFromDevice)return n;if(c){qe.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let w=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:d});n=w.appUrl,i=w.mobileApp,e.nativeApp=i}else qe.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:m,testRunHandler:e}),y=f===N.BROWSERSTACK||f===N.TESTIM_TVC;if(g){let w=t.projectData.type,S=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:w});S&&(qe.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=g),!S&&y&&(qe.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!S&&!y&&qe.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){let{accessToken:n,user:i,host:o,key:a,type:c,apiUrl:l}=t;if(c===N.BROWSERSTACK){let d=`${Xs}/recent_apps`,m=await this.fetchWithUserAndPasswordAuth({url:d,user:i,key:a});return Array.isArray(m)?m.some(u=>u.app_url===e):!1}if(c===N.SAUCELABS){let d=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:d,user:i,key:a})).items.some(u=>u.id===e)}if(c===N.TESTIM_TDC){let d=`${l}/${Cc}/apps`;return l||(d=`${xc}/${Cc}/apps`),(await this.fetchWithTokenAuth({url:d,accessToken:n,authType:"Bearer"})).apps.some(u=>u.app_id===e)}if(c===N.TESTIM_TVC){let d=`${nm}/versions/${e}/info`,m=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:d,accessToken:m,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(u){return u.status!==404&&qe.error("error while verifying app exists on TVC",{error:u}),!1}}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await ve(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 ve(e,void 0,i)}},Ct=new bp});function Ob({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"&&!SI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function EI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==N.TESTIM_TDC)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 II(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 RI(s,e,t,r){let{fullReset:n,setNoReset:i,skipLoadBalancer:o}=e,c=s===N.TESTIM_TDC&&O.flags.enableBatchTDC.isEnabled(),l=O.flags.increaseTDCRequestTimeout.isEnabled();return{["tdc:options"]:{["tdc:capture.video"]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{["tdc:capture.network"]:!1},...o&&{["tdc:controlLock"]:!0},["tdc:retryNewSessionFailure"]:!1,["tdc:sessionTags"]:II(t),["tdc:enableBatch"]:c,...!n&&{"appium:noReset":i},...l&&{["tdc:newCommandTimeout"]:600,"appium:newCommandTimeout":600},...r}}}function Ga(s){return"id"in s?s.id:s.packageName}function xI(s){return{"tdc:app.id":s}}function CI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":n},l=n==null?void 0:n.startsWith("http");n&&!l&&(c=xI(n));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{["appium:options"]:{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":Ga(r)},...n&&c}};case"android":return{["appium:options"]:{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":Ga(r),"appium:appActivity":r.activity??".*"},...n&&c}};default:throw Error(`unsupported mobile project ${s}`)}}function js({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{["appium:options"]:{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Ga(t)},...r&&{[`${i}app`]:r}},...e};case"android":return{["appium:options"]:{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:Ga(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r}},...e};default:throw Error(`unsupported mobile project ${s}`)}}function _b({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a,customCapabilities:c}){let l=RI(o.type,i,n,c);return CI({projectType:s,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Sp({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 Ep({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e;return s||(n!=null&&n.deviceName?n.deviceName:i!=null&&i.deviceNameRegex?i.deviceNameRegex:t==="ios"&&r===N.BROWSERSTACK?"iPhone.*":".*")}function AI(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 Lb(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 PI(s){return Lb(s,e=>e.startsWith("browserstack."),"browserstack.")}function kI(s){return Lb(s,e=>!e.startsWith("browserstack."))}function Db(s){return!s||!Nb(s)?"2.0.0":s}function Nb(s){return s.split(".")[0]==="2"||s.includes("appium2")||["latest","stable"].includes(s)}function Mb({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),c=e==="android"&&(n.test(s)||a),l=e==="ios"&&o.test(s),d=c||l;if(t){let m=Nb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Us(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=r.startsWith(e)?r:`${e}${r}`;t[i]=n}),t}async function OI(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c,shouldRunInEnhancedMode:l,customCapabilities:d}=s,{osVersion:m,deviceName:u}=i,f=(c==null?void 0:c.mobile)||{},{type:h}=o,g=AI(o,e),y=await di({gridId:o.gridId,projectType:e,projectId:i.project,companyId:i.company.companyId}),w=y==null?void 0:y.find(({udid:C})=>{var _;return((_=f.staticAllocation)==null?void 0:_.deviceUdid)===C}),S=(w==null?void 0:w.osVersion)??Sp({osVersion:m,mobileConfig:f}),b=(w==null?void 0:w.name)??Ep({deviceName:u,mobileConfig:f,projectType:e,gridType:h}),v=Je(i.editorUrl,i.project,a.testId,a.testResultId,a.branch),T={"waldo:device":b,"waldo:os_version":S,"waldo:displayName":`${a.testName}-${a.executionId}-${a.testResultId}`,"waldo:externalUrl":v,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:token":g,...d};return T["waldo:options"]||(T["waldo:options"]={}),T["waldo:options"].token||(T["waldo:options"].token=g),js({projectType:e,sessionCaps:T,nativeAppMetadata:t,appPath:r,androidActivityWait:n,shouldRunInEnhancedMode:l})}function _I({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,customCapabilities:c}){let{osVersion:l,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=Sp({osVersion:l,mobileConfig:m}),h=Ep({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),g=(0,At.omit)({...n.saucelabs},["automationName","platformName"]),y={...g["sauce:options"]};delete g["sauce:options"];let w={...c==null?void 0:c["sauce:options"]},S=(0,At.omit)(c,"sauce:options"),b=y.appiumVersion||w.appiumVersion,v=g.platformVersion||S.platformVersion||f;if(Mb({osVersion:v,projectType:s,appiumVersion:b})){let C={debug:!0,networkLogs:!0},_={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:Db(b??"stable"),deviceName:h,tags:Object.values(o)},B={["appium:options"]:{"appium:platformVersion":f,"appium:deviceName":h,...Us(g,Bs),...Us(S,Bs)},"sauce:options":{...C,..._,...(0,At.omit)(y,"appiumVersion"),...(0,At.omit)(w,"appiumVersion")}};return js({projectType:s,sessionCaps:B,appiumPrefix:Bs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let T={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:f,deviceName:h,tags:Object.values(o),name:o.testResultId,build:o.executionId,...g,...y,...S,...w};return js({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function LI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c,customCapabilities:l}){let{osVersion:d,deviceName:m}=i,u=(c==null?void 0:c.mobile)||{},{type:f}=o,h=Sp({osVersion:d,mobileConfig:u}),g=Ep({deviceName:m,mobileConfig:u,projectType:e,gridType:f}),y=PI(i.browserstack),w=(0,At.omit)(kI(i.browserstack),["automationName","platformName","project","build","name"]),S={...l==null?void 0:l["bstack:options"]},b=(0,At.omit)(l,"bstack:options"),v=y.appiumVersion||S.appiumVersion,T=w.platformVersion||b.platformVersion||h,C=O.flags.enableAppium2BrowserStack.isEnabled(),_={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`};if(C||Mb({osVersion:T,projectType:e,isBrowserStack:!0,appiumVersion:v})){let G={..._,userName:o.user,accessKey:o.key,appiumVersion:C?"2.0.1":Db(v),debug:!0,networkLogs:!0},E={["appium:options"]:{"appium:platformVersion":h,"appium:deviceName":g,...Us(w,Bs),...Us(b,Bs)},"bstack:options":{...G,...(0,At.omit)(y,"appiumVersion"),...(0,At.omit)(S,"appiumVersion")}};return js({projectType:e,sessionCaps:E,appiumPrefix:Bs,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}let B={..._,os_version:w.platformVersion||h,device:w.deviceName||g,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...w,...Us(y,"browserstack."),...b,...Us(S,"browserstack.")};return js({projectType:e,sessionCaps:B,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}async function DI(s){if(N.TESTIM_TDC===s.gridInfo.type)return _b(s);if(N.TESTIM_TVC===s.gridInfo.type)return await OI(s);if(N.SAUCELABS===s.gridInfo.type)return _I(s);if(N.BROWSERSTACK===s.gridInfo.type)return LI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function NI(s,e){var l,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,c={};return n==="dynamic"&&(!i&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),i&&(c.manufacturer=i),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function Fb(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}`);Ob({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=Ct.getGridConnection(e),c=await DI(s);if(e.type===N.TESTIM_TDC){let y=NI(r,i==null?void 0:i.mobile);if(!(0,At.isEmpty)(y)){let w=Object.entries(y).map(([S,b])=>b.split(",").map(v=>v===".*"||v==="="?"":`${S}:${v}`).join(",")).join(" ").trim();c["tdc:selector"]=w}}let l=e.type===N.TESTIM_TVC?{alwaysMatch:c}:c,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,vp.default)("2m"),f=(0,vp.default)("12m"),h=Er(O.flags.appiumConnectionRetryCount.getValue(),m),g=Er(O.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:c,connectionRetryTimeout:g,capabilities:l,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function Ub(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;Ob({nativeAppMetadata:r,appPath:i,gridInfo:t}),EI({deviceUdid:l,gridInfo:t,testRunConfig:c});let d=l||((g=(h=c.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await Ct.getGridDirectConnection(t,d),f=_b({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return d&&(f["appium:options"]||={},f["appium:options"]["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Bb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,customCapabilities:i}=s,o={...i,dontStopAppOnReset:!0,fullReset:!1},a=js({projectType:e,sessionCaps:o,nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete a["appium:options"].app,a}function jb(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 vp,At,Bs,SI,Ip=I(()=>{"use strict";vp=R(require("ms"));me();ae();Va();At=require("lodash");F();ye();Bs="appium:",SI=[N.BROWSERSTACK,N.SAUCELABS,N.TESTIM_TDC,N.TESTIM_TVC]});var Ha,Wb=I(()=>{"use strict";Ha=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 qa,Vb=I(()=>{"use strict";F();qa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=pn;this.getLinksFromUnescapeHTML=dn}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 Rp,za,Gb=I(()=>{"use strict";W();Rp=A("mobile-frame-locator-mock"),za=class{foundFrameCallback(){return Rp.info("foundFrameCallback-mock invoked"),{}}locate(){return Rp.info("locate-mock invoked"),{}}async findFrame(){return Rp.info("findFrame-mock invoked"),{}}}});var MI,qb,Hb,$s,xp=I(()=>{"use strict";MI=R(require("webdriverio")),qb=require("@applitools/eyes-sdk-core");Wb();op();W();Vb();ap();Se();dp();Gb();mp();Hb=A("appium-test-player"),$s=class{constructor(e,t,r,n=MI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=ee(),m=new qa(this.driver);this.stepActionFactory=new l(m),$a(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Fs(ha()),this.sessionPlayer=new a(e,{tabService:new Ha,cookieUtils:void 0,FrameLocator:za,portSelector:ma,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:qb.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(c.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()),Hb.info("appium session deleted",{...i}))}catch(o){Hb.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=ee();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function FI(s){return await ve(`${s}/api/status`)}async function zb(s,e){return await ve(`${s}/api/devices/${e}/status`)}async function Kb(s){if((await FI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Jb=I(()=>{"use strict";Ge()});var Xb={};z(Xb,{WorkerLocalTma:()=>kp});var Vr,Cp,Ap,Pp,kp,Yb=I(()=>{"use strict";Ge();Ip();ri();F();W();Ut();xp();Se();Jb();Va();Vr=A("worker-appium"),Cp=class extends Error{},Ap=class extends Error{},Pp=class extends Error{},kp=class extends Wt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new $s(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}=ee(),{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 T;if(Z.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:c}=this.options;await Kb(o);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=c.type,f=this.options.appId;if(f){let{mobileApp:C}=await Ct.getMobileAppDataByAppId({appId:f,projectId:l,token:d});t.nativeApp=C}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,w=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!w)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:S,version:b},v]=await Promise.all([this.getAppStateFromDevice(o,a,w),zb(o,a)]).catch(C=>{throw this.handleDeviceNotFoundError(C),C});if(Vr.info("device status and app state",{deviceStatus:v,appInstalled:S,version:b,executionId:this.executionId,testResultId:this.testResultId}),!S&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!S&&y&&(await this.installApp(o,a,y),Vr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let C={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(T=this.options.projectData)==null?void 0:T.name}-${this.options.project}`},_=Bb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:C,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,customCapabilities:t.customCapabilities}),B={capabilities:{udid:a,..._}};Vr.info("requesting new appium session from TMA",{tmaSessionSettings:B,executionId:this.executionId,testResultId:this.testResultId});let G=await this.requestNewAppiumSessionFromTma(o,B,g);this.sessionData=G;let E=await m.attach({sessionId:G.sessionId,capabilities:_});this.device=await Ct.updateTmaDeviceDetails(a,this.options,t),Vr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:E.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:E.capabilities})}catch(C){throw Vr.error("failed to start application",{err:C}),C}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new Pp(c):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,c=(await ve(o)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Kt(n);await sn(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new Ap(l,{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 Cp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=ee(),{sessionPlayer:o}=r,a=n||"runner";Z.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device,nativeApp:t.nativeApp},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=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(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw Vr.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw Vr.error("failed to run test once",{err:l}),l}}}});var Zb={};z(Zb,{WorkerAppium:()=>Op});var Qb,Gr,Op,eT=I(()=>{"use strict";F();Ip();Qb=require("linkedom");ri();W();Ut();xp();Se();Va();ae();ys();Gr=A("worker-appium"),Op=class extends Wt{initPlayer(t){return new $s(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!==N.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Z.onGetSession(this.id,this.testName,t.runMode);let{driver:c}=n,l=await Ct.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,executionName:t.executionName,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch},f={projectData:this.options.projectData,projectType:o,nativeAppMetadata:m,appPath:l,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a,customCapabilities:t.customCapabilities},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Ct.lockDevice(i,this.options.deviceUdid),h=await Ub(f)):h=await Fb(f),Gr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:jb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await c.remote(h),this.device=await Ct.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Gr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Gr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=ee(),n=async()=>{try{await t.getOrientation()}catch(i){Gr.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"&&hg(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){Gr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===N.TESTIM_TDC?`https://${t}:${r}/v0/${n}/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}=ee(),{sessionPlayer:a}=r,c=n||"runner",l=this.options.timeout;Z.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:w,hostname:S,port:b,path:v}=await Ct.getTDCDeviceConnection(this.options.gridData,y);d=`${w}://${S}:${b}${v}`}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,nativeApp:t.nativeApp},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Qb.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((S,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:S,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 Gr.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 le(u(),l,Pe.TEST_REACHED_CUSTOM_TIMEOUT_MSG)}catch(y){throw Gr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:test"}}});var Ka,tT=I(()=>{"use strict";F();Kn();Q();Ka=class{constructor(e){this.id=e;this.driver=new Nr}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof pe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function rT(){let s=await Promise.any(UI.map(async e=>{try{return await ve(e)}catch{return null}}));return s==null?void 0:s.ip}var UI,Ja,Xa=I(()=>{"use strict";Ge();UI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];Ja=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var sT,Ya,nT=I(()=>{"use strict";sT=R(require("ws"));F();Xa();Ya=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=Ja({timeout:e}),r=new sT.default(this._cdpUrl,t),n=nr(o=>{r.once("open",o)}),i=nr(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([n,i]).then(()=>r),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((c,l)=>{this._cdpCallbacks.set(i,{resolve:c,reject:l})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var Za,_p,Qa,iT=I(()=>{"use strict";F();Za=R(require("chrome-launcher"));Go();nT();Mn();_p=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ya}async init(e){var h,g,y,w;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}=e,m=Vo({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((w=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:w.args)??[],...Za.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await Za.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 Rr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),bs(()=>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}},Qa=class{constructor(e){this.id=e;this.sessionId=ne();this.driver=new _p(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Lp={};z(Lp,{WorkerExtension:()=>mi});function BI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function oT(s){return BI(s)?s:new Error(s)}var st,mi,ec=I(()=>{"use strict";$e();Q();ri();F();W();Ut();ae();tT();iT();dt();st=A("worker-ext"),mi=class extends Wt{initPlayer(){return this.options.useChromeLauncher?new Qa(this.id):new Ka(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:J.EXTENSION,useLocalChromeDriver:this.options.useLocalChromeDriver,customCapabilities:e.customCapabilities})}catch(a){throw st.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:po(),initializedFromCache:mo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Z.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var 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;M("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(d.cdpTestRunner),m,Pe.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof pe))throw u;return st.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 st.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},c=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},l=async()=>{var g;if(M("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Z.onWaitToTestStart(this.id),Z.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(y){throw st.warn("failed to run test via CDP",{err:y}),y}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let S=function(v){e.onCompletedCleanup(),st.warn("on browser closed error detected",{err:v,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(S),m.unregisterToKeepAliveFailed(b),v.type=Yr.BROWSER_CLOSED,w.abort(v)},b=function(v){m.unregisterToClosedBrowser(S),m.unregisterToKeepAliveFailed(b),st.warn("on keep alive failed error detected",{err:v,testResultId:r,executionId:n,testId:i}),v.type=Yr.KEEP_ALIVE_FAILED,w.abort(v)};var f=S,h=b;let y=await e.getRunTestUrl();Z.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,y,u),c(u)]),this.options.testStartTimeout,Pe.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof pe))throw v;st.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let w=new AbortController;m.registerToClosedBrowser(S),m.registerToKeepAliveFailed(b);try{let v=le(e.onCompleted(),this.testRunTimeout,Pe.TEST_COMPLETE_TIMEOUT_MSG),T=await _c(v,w.signal);m.unregisterToClosedBrowser(S),m.unregisterToKeepAliveFailed(b);try{await this.updateTestStatusOnGrid(m,Boolean(T.success),T.reason)}catch(B){st.error("Could not update the grid about the test status",{err:B})}m.isAlive()||(st.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),T.gridIssues="could not validate grid is alive");let C=m.maxKeepAliveGap();return C>=3e4&&(st.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),T.keepAliveIssue=C),{...T,...e.seleniumPerfStats.getStats()}}catch(v){throw st.warn("timeout wait until test completed",{err:v,testResultId:r,executionId:n,testId:i}),oT(v)}finally{m.unregisterToClosedBrowser(S),m.unregisterToKeepAliveFailed(b)}}catch(y){throw st.warn("failed to start url",{err:y}),oT(y)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await l()}catch(d){throw st.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Np={};z(Np,{WorkerExtensionSingleBrowser:()=>Dp});var jI,$I,Dp,Mp=I(()=>{"use strict";$e();F();W();Xu();Ut();ec();jI=A("base-worker"),$I=500,Dp=class extends mi{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await ti(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 Z.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()&&(jI.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;M("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 ie($I)}}});var Fp,tc,aT=I(()=>{"use strict";Kn();ue();$e();Ul();dt();Ou();Q();W();ae();ey();ta();Fp=A("worker-manager"),tc=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 J.SELENIUM:return(await Promise.resolve().then(()=>(yp(),hp))).WorkerSelenium;case J.APPIUM:return t?(await Promise.resolve().then(()=>(Yb(),Xb))).WorkerLocalTma:(await Promise.resolve().then(()=>(eT(),Zb))).WorkerAppium;default:return Jn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Mp(),Np))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(ec(),Lp))).WorkerExtension}else switch(r){case(Br.find(n=>n===r)&&Jn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Mp(),Np))).WorkerExtensionSingleBrowser;case Br.find(n=>n===r):return(await Promise.resolve().then(()=>(ec(),Lp))).WorkerExtension;case ei.find(n=>n===r):return(await Promise.resolve().then(()=>(yp(),hp))).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 M("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,c){if(e&&e.length===0)return;let l=!1,d=0,m=(u,f)=>new Promise(h=>{var q,re,ge,ze,P,L,$,Y;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new ea(r,n,e,i,o,t),this.combinedTestResults={};let w=((q=i.company)==null?void 0:q.ucid)||"",S=(re=i.company)==null?void 0:re.companyId,b=(ge=i.company)==null?void 0:ge.name,v=i.source||"cli",T=i.user,C=(ze=i.company)==null?void 0:ze.planType,_=(P=i.company)==null?void 0:P.isStartUp,B=(L=i.projectData)==null?void 0:L.name,G=($=i.projectData)==null?void 0:$.type,E=i.lightweightMode,k=(Y=i.gridData)==null?void 0:Y.type,D=(De,_t,Ee,bc,wi,Tc)=>(d++,Zf({executionId:r,projectId:g,testId:_t,resultId:Ee,ucid:w,companyId:S,companyName:b,projectName:B,companyPlan:C,source:v,user:T,lightweightMode:E,isStartUp:_,projectType:G,appSource:Tc,gridType:k}),t.testStartAndReport(De,r,Ee,bc,wi)),j=async(De,_t,Ee,bc,wi,Tc)=>{var Md,Fd,Ud;d--;let nt={...(E==null?void 0:E.onlyTestIdsNoSuite)&&{show:!0},...Ee.seleniumStats&&{seleniumStats:Ee.seleniumStats},...Ee.gridIssues&&{gridIssues:Ee.gridIssues},...Ee.keepAliveIssue&&{keepAliveIssue:Ee.keepAliveIssue},...i.host&&{gridHost:i.host}};if(Ee.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(Ee.seleniumPerfMarks),delete Ee.seleniumPerfMarks),i.grid||i.gridId?(nt.gridName=i.grid||((Md=i.gridData)==null?void 0:Md.name),nt.gridType=(Fd=i.gridData)==null?void 0:Fd.type,nt.gridProvider=(Ud=i.gridData)==null?void 0:Ud.provider):i.localTmaUrl?(nt.gridName="local-tma-from-options",nt.gridType="local-tma"):i.useLocalChromeDriver?(nt.gridName="local-chrome-driver-from-options",nt.gridType="local-chrome"):i.useChromeLauncher?(nt.gridName="chrome-launcher-from-options",nt.gridType="local-chrome"):i.browserstack?nt.gridName="browserstack-from-options":i.saucelabs&&(nt.gridName="saucelabs-from-options"),await t.testEndAndReport(De,Ee,r,bc,wi,nt).catch(Ew=>Fp.error("testEndAndReport threw an error",{err:Ew})),wi)return;this.combinedTestResults[Ee.resultId]=Ee,eg({executionId:r,projectId:g,testId:_t,resultId:Ee.resultId,result:Ee,ucid:w,companyId:S,companyName:b,projectName:B,companyPlan:C,source:v,user:T,lightweightMode:E,logger:Fp,isStartUp:_,projectType:G,appSource:Tc}),c&&!Ee.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},V=(De,_t)=>{this.combinedTestResults[_t.resultId]=_t,t.onTestIgnored(De,_t.resultId),d--,(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},K=(De,_t)=>t.onGridSlot(De,_t);for(i.userData={loginData:{...Ar(),refreshToken:lo(),authData:Ar(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:be()},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,D,j,K,V)});try{let u=await Mt(),f=await uo(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),l)throw new rr;return h}catch(u){throw Fp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var fi,cT,rc,Up,Bp,Hr,jp=I(()=>{"use strict";fi=R(require("lodash"));F();W();ue();ae();$e();ds();Fl();Ul();ye();cT=require("uuid");sg();F();Ut();$g();Q();aT();me();ta();({CLI_MODE:rc}=Jt),Up=A("test-plan-runner"),Bp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return Bp._id}async runTestAllPhases(e,t,r,n,i,o,a,c){let l={},d=new tc(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,w=await d.runTests(e,c,o,a,i,n,g,y);Object.assign(l,w)},u=async()=>{let g=_i||i.parallel,y=!1;M("right before this.workerManager.runTests");let w=await d.runTests(t,c,o,a,i,n,g,y);M("right after this.workerManager.runTests"),Object.assign(l,w)},f=async()=>{let g=i.afterParallel||1,y=!1,w=await d.runTests(r,c,o,a,i,n,g,y);Object.assign(l,w)};tg({executionId:o,projectId:i.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),l}catch(g){if(Up.error("error running test plan",{err:g}),g instanceof rr)return c.markAllQueuedTests(o,he.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var w,S,b,v;if((w=i.lightweightMode)!=null&&w.disablePixelValidation)return;if(i.mode===rc.SELENIUM)try{let[{getSessionPlayer:T},{makeSDK:C}]=await Promise.all([Promise.resolve().then(()=>(Se(),dr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:_}=T();await le(_.closeBatch(o,C),1e4);return}catch{}let y;try{if(!((v=(b=(S=i.company)==null?void 0:S.activePlan)==null?void 0:b.premiumFeatures)!=null&&v.applitools)||(y=await Gp(i.project),fi.default.isEmpty(y)||!o))return;let{runKey:T,url:C}=y,_=require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}});await le(_.closeBatches({settings:{batchIds:[o],serverUrl:C,apiKey:T}}),1e4)}catch{}}}async runTestPlan(e,t,r,n,i,o,a,c){var b,v,T;let l=ne(),d=n.project;hm(l),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Do(m,n,o,a),f=fi.default.chain(m).map(C=>{var _;return((_=C.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(C=>C.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,d,this.startTime,i,g);M("before testListInfoPromise");let w=await y;(T=n.lightweightMode)!=null&&T.onlyTestIdsNoSuite||Z.onTestPlanStarted(w.beforeTests,w.tests,w.afterTests,i,l,c,h),M("before runTestAllPhases");let S=await this.runTestAllPhases(w.beforeTests,w.tests,w.afterTests,a,n,l,i||"All Tests",u);return M("before executionEnd"),await u.executionEnd(l),M("after executionEnd"),{results:S,executionId:l,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(de.colorString(de.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await $p(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await Wp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){Up.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return fi.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:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await oe(e.testPlanIds,async d=>{let m=await gi(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 oe(e.testPlan,async d=>{let m=await gi(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 gi(o,e.testPlan,e.testPlanIds,t,e.intersections);let c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new x(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new x(`no test to run in test plan ${e.testPlan}`)}return e.mode!==rc.APPIUM&&await Ku(e,r(l)),await oe(c,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 $f(e,d);let f=u.overrideExecutionName||d.name;return await oe(l[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Z.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let w=Object.keys(n[m]).map(T=>({executionId:T,status:zu(n[m][T])})),S=Object.keys(n[m]).map(T=>n[m][T]).reduce((T,C)=>Object.assign(T,C),{}),b=zu(S);Object.assign(i,S);let v=b?w[0].executionId:w.find(T=>!T.status).executionId;return await Vp(o,m,{success:b,executions:w,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var c;Up.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await ry(e,t);if(M("after getSuite"),!((c=r==null?void 0:r.tests[0])!=null&&c.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;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===rc.APPIUM&&(a=await pi({appId:e.appId,projectId:e.project})),await oe(r.tests,async l=>{if(a&&l.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=l[0];m.resultId=e.resultId,l=[m]}e.mode!==rc.APPIUM&&await Ku(e,l),M("right before runTestPlan");let d=await this.runTestPlan([],l,[],e,i,null,t,o);return M("right after runTestPlan"),await Z.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=An(),r=[];await this.reportTestRunnerStarted(e.project,e),cn(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=fi.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Hr=Bp;Hr._id=(0,cT.v4)()});var ke={};z(ke,{addTestRetry:()=>yu,clearTestResult:()=>Hu,deleteCloudflareTunnel:()=>Zp,fetchLambdatestConfig:()=>wu,fixGridAppIDStructure:()=>wp,forceUpdateCloudflareTunnelRoutes:()=>Qp,getAllGrids:()=>Ml,getAppDetails:()=>pi,getApplitoolsIntegrationData:()=>Gp,getBrowserStackSessionMetaData:()=>YI,getCloudflareTunnel:()=>Yp,getCustomCapabilitiesByName:()=>td,getEditorUrl:()=>KI,getFileUrl:()=>zp,getGridSlot:()=>Nl,getHybridGridProvider:()=>Dl,getLabFeaturesByProjectId:()=>_u,getMobileDevicesFromGrid:()=>di,getRealData:()=>uu,getS3Artifact:()=>Un,getS3ArtifactText:()=>lu,getSuiteTestList:()=>Ju,getTestPlan:()=>zI,getTestPlanTestList:()=>gi,getTestResults:()=>Ur,getUsageForCurrentBillingPeriod:()=>Jp,initializeUserWithAuth:()=>Xp,isTestResultCompleted:()=>Gu,keepAliveCompanySlots:()=>au,keepAliveGrid:()=>_l,loadSfdcCredential:()=>Kp,loadTest:()=>Qn,releaseCompanySlot:()=>iu,releaseGridSlot:()=>Ll,reportExecutionFinished:()=>No,reportExecutionStarted:()=>hu,reportRunnerFinished:()=>Wp,reportRunnerStarted:()=>$p,requestCompanySlot:()=>nu,saveRemoteStep:()=>Du,saveTestPlanResult:()=>Vp,updateCompanySlot:()=>ou,updateExecutionTests:()=>gu,updateRemoteRunFailure:()=>ed,updateTestDataArtifact:()=>Mo,updateTestResult:()=>aa,updateTestStatus:()=>_r,uploadAppToGrid:()=>Tp,uploadRunDataArtifact:()=>qu,validateUserAccessKey:()=>kl});async function Ws(){let s=await Mt();if(!s)throw new Error("Failed to get token from server");return{[Zc]:Hr.id,Authorization:`Bearer ${s}`}}async function Ce({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await Ws(),o={...t,...i};return Ve({url:`${be()}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function HI(s,e,t,r={},n=void 0){let i=await Ws(),o={...r,...i};return await sn(`${be()}${s||""}`,e,t,o,n)}async function hi(s,e){let t=await Ws();return await Fc(`${be()}${s||""}`,e,t)}async function uT(s,e){let t=await Ws();return await rn(`${be()}${s||""}`,e,t)}async function qI(s,e){let t=await Ws();return await Mc(`${be()}${s||""}`,e||void 0,t)}async function xe(s,e,t,r){let n=await Ws();return await ve(`${be()}${s||""}`,e||void 0,n,r,t)}function Un(s,e){return(0,te.default)(()=>xe(`/storage${s}`,null,{isBinary:!0},e),{retries:se,factor:1})}function zp(s,e){return(0,te.default)(()=>xe(`/files/fileUrl?${s}`,null,{isBinary:!0},e),{retries:se,factor:1})}function lu(s){return(0,te.default)(()=>qI(`/storage${s}`))}async function $p(s,e){return await Ce({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function Wp(s){return await uT("/test-runner",{projectId:s})}async function zI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,te.default)(()=>xe("/testPlan",{projectId:s,name:e.join(",")}),{retries:se,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function Kp({branch:s,projectId:e}){let t=await(0,te.default)(()=>xe(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:se,factor:1});return t==null?void 0:t.sfdcCredential}function Qn({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,te.default)(()=>xe(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:se,factor:1})}function Vp(s,e,t){return(0,te.default)(()=>Ce({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:se,factor:1})}function _r(s,e,t,r,n,i,o=se){return(0,te.default)(()=>hi("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:WI,...i}),{retries:o,factor:1})}function gu(s,e,t,r,n,i,o,a){return(0,te.default)(()=>hi("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:se,factor:1})}async function hu({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(bo(),Xf));return Ce({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:c,isLocalRun:l}},retry:3})}function No(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,te.default)(()=>hi("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:se,factor:1})}async function gi(s,e,t,r,n){return(0,te.default)(()=>Ce({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:se,factor:1})}function Ju({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}){return(0,te.default)(()=>Ce({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}}),{retries:se,factor:1})}async function pi({appId:s,projectId:e}){try{let t=await(0,te.default)(()=>xe(`/mobile-app/app/${s}?projectId=${e}`),{retries:se,factor:1});return Gt.omit(t,"version")}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function Jp(s){try{return await(0,te.default)(()=>xe(`/plan/project/${s}/usage-current-billing-period`),{retries:se,factor:1})}catch(e){Vt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Gu(s,e,t){return(0,te.default)(()=>xe(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:se,factor:1})}function Ur(s,e,t,r){return(0,te.default)(()=>xe(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:se,factor:1})}function _l(s,e){return Ce({url:`/grid/keep-alive?reqId=${ne()}`,body:{projectId:s,slots:e},timeout:1e4})}function Ll(s,e,t,r,n){return Ce({url:`/grid/release?reqId=${ne()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Dl(s){return Ce({url:"/grid/hybrid/provider",body:s})}function Nl(s){return(0,te.default)(()=>xe("/grid/grid-slot",{...s,reqId:ne()}),{retries:se,factor:1})}async function Xp({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d}){var m,u;try{return await(0,te.default)(()=>Ve({url:`${be()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d},timeout:6e4}),{retries:se,factor:1})}catch(f){if(Vt.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new x("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((u=f.code)!=null&&u.includes("ENOTFOUND"))throw new x("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",y=h.clientMessage.bgColor||"bgBlack";console.log(Hp.default[y](Hp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Vt.error("Error parsing error message from server",f)}throw f}}async function KI(){if(it)return{editorUrl:it};try{return await(0,te.default)(()=>xe("/system-info/editor-url"),{retries:se,onFailedAttempt:s=>{if(s.attemptNumber>=se)throw s},factor:1})}catch(s){return Vt.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Ml(s){return(0,te.default)(()=>xe("/grid",{companyId:s}),{retries:se,factor:1})}function uu(s,e,t){return(0,te.default)(()=>xe(`/real-data/${e}?${t}&projectId=${s}`),{retries:se,factor:1})}function aa(s,e,t,r,n){return(0,te.default)(()=>Ce({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:se,factor:1})}function Hu(s,e,t,r){return(0,te.default)(()=>Ce({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:se,factor:1})}function Du(s,e,t,r){return(0,te.default)(()=>Ce({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:se,factor:1})}function JI(s){return s.startsWith("/")?s:`/${s}`}function XI(s,e,t){let r=JI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function pT(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${ne()}${o||""}`,c=`${e}/${t}/${a}`,l=XI(c,GI,s),d=Buffer.from(lT.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,te.default)(()=>HI(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:se,factor:1}),l}function yu({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,te.default)(()=>Ce({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:se,factor:1})}async function Gp(s){try{return await xe(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Vt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Yp(s,e){try{return await hi("/tunnel",{companyId:s,routes:e})}catch(t){return Vt.warn("could'nt get tunnel.",{err:t}),{}}}async function Qp(s,e){try{return await Ce({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Vt.warn("could'nt get tunnel.",{err:t});return}}async function Zp(s,e){try{return await uT(`/tunnel/${e}`,{companyId:s})}catch(t){Vt.warn("could'nt get tunnel.",{err:t});return}}function ed(s){return Ve({url:`${be()}/result/remoteRunFailure`,body:s})}async function di({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${VI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,te.default)(()=>xe(i,{projectId:s}),{retries:se,factor:1})}catch(o){return Vt.warn("could'nt get devices from grid.",{err:o}),null}}async function Tp({projectId:s,gridId:e,app:t,timeout:r}){return(0,te.default)(()=>Ce({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:se,factor:1})}async function wp(s){return(0,te.default)(()=>Ce({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:se,factor:1})}async function nu(s,e){return(0,te.default)(()=>Ce({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:se,factor:1})}async function iu(s,e,t){return(0,te.default)(()=>Ce({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:se,factor:1})}async function ou(s,e,t){return(0,te.default)(()=>hi("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:se,factor:1})}function au(s,e,t){return Ce({url:`/slot-management/keep-alive?reqId=${ne()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function YI(s,e){return await ve(`${Xs}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function kl(s){try{return await xe("/v2/project/validateUserAccessKey",s),!0}catch(e){return Vt.error("error validating user access key",{error:e}),!1}}async function td(s,e){let[t]=await xe("/capabilities?",{projectId:s,name:e});return t}var Hp,Gt,lT,te,qp,WI,Vt,se,VI,GI,wu,_u,qu,Mo,ye=I(()=>{"use strict";Hp=R(require("chalk")),Gt=R(require("lodash")),lT=R(require("pako"));F();ue();ae();Ge();dt();te=R(require("p-retry")),qp=R(require("object-hash"));Q();W();jp();WI=ot(),Vt=A("testim service api"),se=3,VI="/grid",GI="test-result-artifacts";wu=async(s,e)=>(0,te.default)(()=>xe("/grid/lt/config",{companyId:s,...e&&{projectId:e}}),{retries:se,factor:1}),_u=async s=>(0,te.default)(()=>xe(`/labFeature/v2/project/${s}`),{retries:se,factor:1});qu=Gt.memoize(async(s,e,t,r)=>{if(!Gt.isEmpty(r))return await pT(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,qp.default)(r)}:${e}:${t}`),Mo=Gt.memoize(async(s,e,t,r,n)=>!r||Gt.isEmpty(r)?void 0:await pT(s,e,t,JSON.stringify((()=>{let o=Gt.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:Xc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,qp.default)(r)}:${e}:${t}`)});function sc(){return ot()}var rd=I(()=>{"use strict";F()});function eR(s){J.EXTENSION!==s&&process.nextTick(()=>{try{(Se(),Ke(dr)).getSessionPlayer()}catch{}})}function tR(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let n=r.color||"yellow",i=r.bgColor||"bgBlack";console.log(sd.default[i](sd.default[n](r.text)))})}function rR(s,e){let{serviceUrl:t}=s;Ys(t),ut(async()=>s,Qr.CACHE_FN_NAME,Qr.TTL,{serviceUrl:t})(),Ht.setRegion(Gg[Ss(e)])}async function yi(s){var b;let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?ZI:QI,f=sc(),h=Hc(),g=await gf(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await rT()}catch(v){dT.error("failed to get public ip",v)}let w=!0;M("before initializeUserWithAuth");let S=await ut(async()=>(eR(a),w=!1,await Xp({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:y,gridId:c,grid:l,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:c,grid:l,publicIp:y})();return tR(S),rR(S.clientConfig,e),s.publicIps=[S.clientPublicIp],M("after initializeUserWithAuth"),y&&S.clientPublicIp&&S.clientPublicIp!==y&&(dT.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:S.clientPublicIp}),s.publicIps.push(y)),Nf(S.authData,{projectId:e,token:t,userAccessKey:r,publicIp:S.clientPublicIp,initializedFromCache:w}),Jf((b=S.clientConfig)==null?void 0:b.segmentKey),S}var sd,dT,QI,ZI,mT=I(()=>{"use strict";sd=R(require("chalk"));$e();ye();Xt();dt();Xa();ae();W();me();rd();F();us();ue();Uo();Pr();dT=A("initializeUserWithAuth"),QI=1e3*60*5,ZI=1e3*60*60*10});async function hT(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await co():s.chromeBinaryLocation,e=hn({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==J.EXTENSION&&await xr(s.playerLocation,s.canary),s.mode!==J.SELENIUM&&s.mode!==J.APPIUM&&!s.ext&&await wl(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Tl(s.installCustomExtension,n)}return await e,t}async function yT(s){var o;sR.info("prepare MockNetwork",{location:s});let e=await Wc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>fT*1e6)throw new Error(`${nd} exceeded ${fT}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${nd} cannot be parsed.${nc.EOL}${a}`)}let n=new gT.default;if(!n.validate(ll,r)){let a=(o=n.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(nc.EOL);throw new Error(`${nd} is malformed.${nc.EOL}${a}`)}return r.entries}var nc,gT,fT,nd,sR,id=I(()=>{"use strict";nc=R(require("node:os"));F();zm();bn();gT=R(require("ajv"));ae();Il();W();mT();fT=1,nd="JSON file supplied to --mock-network-pattern",sR=A("prepare runner")});function ST(s){return s.start&&ms(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function ET(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new x("Agent port is not number");let t=Fo(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var IT=I(()=>{"use strict";Wn();Pr();Q()});var Vs,ld,RT=I(()=>{"use strict";Vs="SECRETS",ld={get secretsKey(){return Vs},get proxySecrets(){return new Proxy({},{get(s,e){return`${Vs}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[Vs]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(Vs):JSON.stringify(s).includes(Vs)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${Vs}\\.\\w+`,"g"));return r==null||r.map(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${r}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(n);if(l){let d=l[1];o[c]=e[d]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(n);if(l){let d=l[1];o[a]=e[d]??c}}else typeof c=="object"&&c!==null&&i(c)})};i(s)}}});var fd={};z(fd,{doLogin:()=>md,getProjectId:()=>lR,getToken:()=>uR});async function lR(){return AT("projectId")}async function uR(){return AT("token")}function CT(s,e){return Promise.race([s,ie(e).then(()=>{throw new pe("timeout")})])}async function pR(){let s=(await import("express")).default(),e=async function(){return CT(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ye(),ke)),{editorUrl:n}=await r();Po(`${n}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${it||wr}`)}return await e}async function md({overwriteExisting:s=!0,projects:e=null}={}){let t=ud.homedir(),r=pd.join(t,".testim");if(await Te(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await CT(pR(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,c.succeed(),await xT(r,i);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=l.project.ci.token,i.projectId=l.project.id,await xT(r,i);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function xT(s,e){await dd.promises.writeFile(s,oc.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function AT(s){let e=ud.homedir(),t=pd.join(e,".testim"),r=await Te(t),n={};if(r)try{n=oc.parse((await dd.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var ud,pd,oc,dd,ac=I(()=>{"use strict";ud=R(require("os")),pd=R(require("path")),oc=R(require("yaml"));F();dd=require("fs");Q();eu();ue()});var FT={};z(FT,{process:()=>wR,program:()=>p});var hd,LT,cc,DT,kt,_e,NT,dR,Ue,mR,bd,fR,gR,kT,MT,bi,yd,lc,Td,gd,Pt,OT,hR,yR,p,bR,TR,_T,wR,UT=I(()=>{"use strict";hd=R(require("ms")),LT=R(require("chalk")),cc=R(require("node:fs")),DT=R(require("node:url")),kt=R(require("lodash")),_e=R(require("node:path"));F();Wn();IT();Xt();NT=require("commander");ae();Q();qr();F();me();RT();ta();Uo();ue();vu();dR=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ue=(s,e)=>(e.push(s),e),mR=s=>(e,t)=>{if(t!==void 0)throw new x(`The ${s} flag can only be specified once.`);return e},bd=new NT.Command,fR=s=>s.split(","),gR=(s,e)=>!s||s.length===0?e:s,kT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],MT=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}bd.help(g=>g.split(`
405
405
  `).filter(w=>!t(w)&&!e(w)&&!s(w)&&!r(w)&&!n(w)&&!a(w)&&!o(w)&&!i(w)&&!c(w)&&!l(w)&&!d(w)&&!m(w)&&!u(w)&&!f(w)&&!h(w)).join(`
406
406
  `))},bi=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(LT.default.yellow(`
407
407
  WARNING: ${s} is deprecated. ${t}
408
- `))},yd=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:lc,argv:Td,exit:gd,cwd:kt}=global.process,OT={development:{usw2:{servicesUrl:"https://services.dev.testim.io"},euc1:{servicesUrl:"https://services.dev.eu.testim.io"}},staging:{usw2:{servicesUrl:"https://services.staging.testim.io"},euc1:{servicesUrl:"https://services.staging.eu.testim.io"}},production:{usw2:{servicesUrl:"https://services.testim.io"},euc1:{servicesUrl:"https://services.eu.testim.io"}}},hR=async s=>{let e=Is(s),t=await cs(es.CACHE_FN_NAME);if(t&&t.region===e){Qs(t.servicesUrl);return}let n=(OT[Xs]||OT.production)[e]||{servicesUrl:"https://services.testim.io"};lc.SERVICES_HOST||Qs(n.servicesUrl)},yR=new Set(["trace","debug","info","warn","error","silent"]);el(Td,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));bd.description("Testim.io CLI").option("-h --help","output usage information",MT).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-data [test-data]","test data file name to include in the test run").option("--test-config [test-config]","test config name to override for all tests in current execution",Be,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Be,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Be,[]).option("--test-id [test-id]","test ID to run",Be,[]).option("-l, --label [label]","labels to search test by",Be,[]).option("-n, --name [test-name]","test name to run",Be,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",fR).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Be,[]).option("--test-plan-id [test-plan-id]","test plan to run",Be,[]).option("--suite [suite-name]","suite to run",Be,[]).option("--suite-id [suite-id]","suite ID to run",Be,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",Be,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(lc.TESTIM_TEST_START_TIMEOUT)||2*60*1e3).option("--timeout [test-timeout]","Test run timeout in milliseconds",Number).option("--browser-timeout [open-browser-timeout]","Get browser from grid timeout in milliseconds",Number).option("--new-browser-wait-timeout [max-wait-to-browser]","Maximum get browser wait in minutes",Number).option("--get-browser-timeout [get-browser-timeout]","Timeout for a single attempt to get browser from the grid configured in the project's plan",Number).option("--get-browser-retries [get-browser-retries]","Number of attempts to get browser from the grid configured in the project's plan",Number).option("--get-session-timeout [get-session-timeout]",'Timeout for "/session" request to the selenium server',Number,(0,hd.default)("90s")).option("--get-session-retries [get-session-retries]",'Retries for "/session" request to the selenium server',Number,3).option("--driver-request-timeout [driver-request-timeout]","Timeout for any WebDriver request to the grid server",Number,(0,hd.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).option("--local-tma-url [local-tma-url]","use a local TMA instance for appium session").option("--use-local-chrome-driver [use-local-chrome-driver]","use a local ChromeDriver instance instead of a selenium grid").option("--chrome-binary-location [chrome-binary-location]","Chrome binary location").option("--use-chrome-launcher","use a local Chrome installation without selenium").option("-mnh --mock-network-har","use the HAR file configured in the Testim editor to mock network traffic").option("-mnp --mock-network-pattern [local file location path]","use a JSON rule file to mock network traffic (Rule file schema: https://help.testim.io/page/mocking-network-traffic)").option("-omf --override-mapping-file [local file location path]","pass map file location to override mock network (see schema: https://help.testim.io/page/mocking-network-traffic)").option("-dmn --disable-mock-network","Disable mock mode for the entire CLI run").option("--run-quarantined-tests","Run quarantine tests").option("--collect-code-coverage","collect code coverage for all js files under base url").option("--code-coverage-url-filter [url pattern]","collect code coverage for all js files matching url filter (url including asterisk)").option("--code-coverage-report-path [path]","where to save coverage report (default ./coverage)").option("--code-coverage-source-map-path [path]","path of source code").option("--code-coverage-reporter [reporter]",`set code coverage reporter (default html and text), options: ${yd.join("/")}`,Be,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Be,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--sealights-lab-id [sealights-lab-id]","SeaLight Lab ID").option("--sealights-build-session-id [sealights-build-session-id]","SeaLight Session Build ID").option("--sealights-test-stage [sealights-test-stage]","SeaLight Test Stage Name").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Be,[]).option("--label-intersection-operand [operand]",'Run only tests that match either all the labels with the "AND" operand, or at least one of the labels with the "OR" operand',mR("--label-intersection-operand")).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",Be,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",Be,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").option("--custom-capabilities-name <name>","name of pre-created custom capabilities item").option("--custom-capabilities-file <path>","path to a JSON file with capabilities settings").parse(Td);p=bd.opts(),bR=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},TR=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},_T=s=>{var r;if(!O.flags.secrets.isEnabled({projectId:p.project}))return;let t=cc.readFileSync(s);(r=ld)!=null&&r.containsSecrets(t.toString())&&ld.injectProxySecretsStoreToGlobal()},wR=async()=>{var S,b,v,T,C,_,B,G;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={},n;if(!Td.slice(2).length)throw MT(),new Jr;if(p.version){let E="Testim CLI Version: ";lc.npm_package_version&&(console.log(E,lc.npm_package_version),gd(0));let k=at();k&&(console.log(E,k),gd(0)),console.log("Could not find version, please check the package.json manually"),gd(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&of(),p.clearFileCache&&ls();let i=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(i){let E=_e.resolve(i);sf(E)}if(p.usePrefechedData&&af(),p.playerRequirePath){let E=_e.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",E);let k=_e.join(E,"tsconfig.node.json"),j=require("ts-node").register({project:k,ignore:[/node_modules/,new RegExp(`^${Ot.escapeRegExp(_e.relative(kt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:j.config.options.paths,baseUrl:j.config.options.baseUrl}),(Se(),Je(dr)).options.playerPath=E;let K=require("node:module"),q=K.prototype.require;K.prototype.require=function(ge){return ge==="rox-alias"?q.call(this,"rox-node"):ge==="canvas"?{}:q.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=cc.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new x("missing --proxy option");if(ST(p))return ET(p);try{let E={};p.configFile?(_T(p.configFile),E=require(_e.join(kt(),p.configFile)).config):p.optionsFile&&(E=require(_e.join(kt(),p.optionsFile))),E&&typeof E.then=="function"&&(E=await E),Object.keys(E).forEach(k=>{let D=dR(k);p[D]=gR(p[D],E[k])})}catch(E){throw E.message=`Unable to read options file: ${E.message}`,E}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((S=p.testConfig)==null?void 0:S.length)||((b=p.testConfigId)==null?void 0:b.length),a=((v=p.testPlan)==null?void 0:v.length)||((T=p.testPlanId)==null?void 0:T.length),c=((C=p.suite)==null?void 0:C.length)||((_=p.suiteId)==null?void 0:_.length);if(p.customCapabilitiesFile&&p.customCapabilitiesName)throw new x("You can either use --custom-capabilities-name or --custom-capabilities-file");if((p.customCapabilitiesFile||p.customCapabilitiesName)&&(p.browserstackOptions||p.sauceOptions||p.seleniumCapsFile||p.perfectoOptions))throw new x("Custom capabilities parameters can't be used together with --browserstack-options, --sauce-options, --selenium-caps-file or --perfecto-options parameters");if(p.customCapabilitiesFile)try{n=require(_e.join(kt(),p.customCapabilitiesFile)),$o(n)}catch(E){throw E instanceof x?E:new x(`Failed to parse custom capabilities file: ${E.message}`)}if(p.seleniumCapsFile){bi("--selenium-caps-file","--custom-capabilities-name or --custom-capabilities-file");try{r=require(_e.join(kt(),p.seleniumCapsFile))}catch(E){throw new x(`Failed to parse selenium caps file file error: ${E.message}`)}}if((B=p.reporters)!=null&&B.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new x("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new x("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new x("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(_e.join(kt(),p.chromeExtraPrefs))}catch(E){throw new x(`Failed to read/open chrome extra prefs file error: ${E.message}`)}if(p.chromeExtraArgs){let E=p.chromeExtraArgs.split(",");for(let k of E){let[D]=k.split("=");kT.includes(D)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(k),D==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${D}), allowed values: ${JSON.stringify(kT)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&_T(p.paramsFile),s={...s,...require(_e.join(kt(),p.paramsFile))}}catch(E){throw new x(`Failed to read/open params file error: ${E.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(E){throw new x(`Failed to parse params string error: ${E.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new x("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(bR(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions){bi("--sauce-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(_e.join(kt(),p.sauceOptions)),k=E.platformName&&["ios","android"].includes(E.platformName.toLowerCase());if(E.browserName){let j=E.browserName.toLowerCase();switch(j){case"microsoftedge":p.browser="edge";break;default:p.browser=j}}p.browser==="edge"&&parseFloat(E.version)>=79&&(p.browser="edge-chromium");let D=parseFloat(E.version)<50&&!["dev","beta"].includes(E.version);if(!k&&p.browser==="chrome"&&D)throw new x("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...E}}catch(E){throw new x(`Failed to parse saucelabs options file error: ${E.message}`)}}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new x("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(TR(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions){bi("--browserstack-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(_e.join(kt(),p.browserstackOptions)),k=E.platform&&["mac","android"].includes(E.platform.toLowerCase());if(E.browserName&&(p.browser=E.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(E.browser_version)>=79&&(p.browser="edge-chromium"),!k&&parseFloat(E.browser_version)<50&&p.browser==="chrome")throw new x("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...E}}catch(E){throw new x(`Failed to parse browserstack options file error: ${E.message}`)}}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions){bi("--perfecto-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(_e.join(kt(),p.perfectoOptions)),k={location:"US East",securityToken:p.perfectoToken};p.perfecto={...k,...E}}catch(E){throw new x(`Failed to parse perfecto options file error: ${E.message}`)}}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let E=require(_e.join(kt(),p.testobjectOptions)),k={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...k,...E}}catch(E){throw new x(`Failed to parse test object options file error: ${E.message}`)}let l={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId,testStage:p.sealightsTestStage}};if(p.testOptimization=l,!p.project){let k=await(await Promise.resolve().then(()=>(ac(),fd))).getProjectId();if(k)p.project=k;else throw new x("missing project-id info, either --login to provide new credentials or use --project <project-id>")}hR(p.project),O.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=Math.max(p.browserTimeout,p.getSessionTimeout),p.driverRequestTimeout=Math.max(p.browserTimeout,p.driverRequestTimeout);let m=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let k=await(await Promise.resolve().then(()=>(ac(),fd))).getToken();if(k)p.token=k;else throw new x("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let u=E=>E<=0||!Number.isInteger(E);if(u(p.retries))throw new x("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new x("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(u(p.browserTimeout))throw new x("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(u(p.newBrowserWaitTimeout))throw new x("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(u(p.timeout))throw new x("test run timeout could not be a negative number, --timeout <run-timeout>");if(u(p.beforeParallel))throw new x("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(u(p.parallel))throw new x("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(u(p.afterParallel))throw new x("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![J.EXTENSION,J.SELENIUM,J.APPIUM].includes(p.mode))throw new x(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...$r,...ei].includes(p.browser))throw new x(`browser ${p.browser} is not supported`);if(p.mode!==J.SELENIUM&&p.disableNativeEvents)throw new x("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!yR.has(p.appiumLogLevel))throw new x(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new x("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||c||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new x("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!a&&(p.beforeParallel!==1||p.afterParallel!==1))throw new x("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new x("please define exactly one of --grid or --grid-id or --host");if((G=p.host)!=null&&G.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=DT.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(k=>k.trim()).filter(Boolean);let E=p.resultLabel.filter(k=>k.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&Rr()&&p.resultLabel.unshift(Rr()),E.length)throw new x("A result label cannot exceed 250 characters")}let h=Fo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new x("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new x("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new x("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(c||p.name.length||p.testId.length||p.label.length||a))throw new x("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!Ot.inRange(Ot.parseInt(p.setRetention),1,11))throw new x("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let g="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new x(`--mock-network-har ${g}`);if(p.mockNetworkPattern)throw new x(`--mock-network-pattern ${g}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new x("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new x("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new x("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new x("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Ot.difference(p.codeCoverageReporter,yd).length){let E=Ot.difference(p.codeCoverageReporter,yd);throw new x(`invalid --code-coverage-reporter parameters ${E.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let y={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},w=Object.keys(y).filter(E=>Boolean(p[E]));if([J.APPIUM,J.SELENIUM].includes(p.mode)&&w.length){let E=w.length>1?"are":"is";throw new x(`${w.map(k=>y[k]).join(" and ")} ${E} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let E=cc.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(E)}catch(E){throw new x(`failed to parse field file error: ${E.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new x("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.labelIntersectionOperand===!0)throw new x("The --label-intersection-operand flag requires a value. Please provide a value after the flag.");if(p.labelIntersectionOperand&&!Object.values(an).includes(p.labelIntersectionOperand))throw new x(`The --label-intersection-operand flag must be one of the following values: ${Object.values(an).join(", ")}`);if(p.labelIntersectionOperand&&Ot.isEmpty(p.intersectWithLabel))throw new x("The --label-intersection-operand flag must be used together with the --intersect-with-label flag.");if(p.highSpeed&&(bi("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new x("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new x("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new x("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let E={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},k=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...E,...k}}catch(E){throw new x(`failed to parse lightweightMode settings error: ${E.message}`)}else p.turboMode&&![J.APPIUM,J.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[J.APPIUM,J.SELENIUM].includes(p.mode)&&console.warn(`
409
- When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new x("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?Rr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,testOptimization:p.testOptimization,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionPath:p.extensionPath,extensionLocation:[p.extensionPath].filter(Boolean),playerLocation:p.playerPath||h,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:m,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections,labelIntersectionOperand:p.labelIntersectionOperand},testDataFileName:p.testData,downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps,customCapabilities:n,customCapabilitiesName:p.customCapabilitiesName}}});var wd,vR,Hs,BT,jT,vd,$T,WT=I(()=>{"use strict";F();Q();W();Ss();wd=A("testimNgrok"),vR=".whitelisted-ngrok.testim.io",Hs="",jT=async(s,e={})=>{if(!e.ngrokToken)throw new x("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${ne()}-${s.projectData.projectId}${vR}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let i=await(await Ue("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(wd.info("replace https to http"),Hs=i.replace("https://","http://")):Hs=i,s.tunnelDiagnostics&&vd(),s.baseUrl=Hs},vd=async(s=!0)=>{try{let t=(await Ue("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===Hs);console.log("ngrok stats",n),wd.info("ngrok stats",{tunnel:n})}catch(e){wd.error("error collecting ngrok stats",{err:e})}s&&(BT=setTimeout(()=>vd(),1e4))},$T=async s=>{if(!Hs)return;clearTimeout(BT),s.tunnelDiagnostics&&await vd(!1),await(await Ue("ngrok")).disconnect(Hs)}});var _t,Id,VT,Rd,GT,uc,ER,IR,Ed,RR,pc,Sd,xR,dc,Ti,CR,AR,HT,qT,zT=I(()=>{"use strict";_t=R(require("node:os")),Id=R(require("node:path")),VT=R(require("portfinder")),Rd=R(require("node:fs")),GT=R(require("node:child_process"));F();ye();W();uc=A("testimCloudflare"),ER="https://github.com/cloudflare/cloudflared/releases/download/2025.11.1/",IR={win32ia32:{path:"cloudflared-windows-386.exe",sha256:"1e76c0d4e6ff2576db46ad1a7397415729fbaf886b22aa49327f66185a2e8fc8"},win32x64:{path:"cloudflared-windows-amd64.exe",sha256:"413f9b24dc6e61a455564651524f167b8ce29ac4ccd40703dea7af93cd37ed39"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",sha256:"155a288fef19dba08f0c7145c16a207baf137462d8a1289a78bf8564f9e51244",extract:!0},darwinarm64:{path:"cloudflared-darwin-arm64.tgz",sha256:"45cfbb59a720f60b873906aa6469f8c4058f26be6d351c3e2920bc9cb4714273",extract:!0},linuxia32:{path:"cloudflared-linux-386",sha256:"bec7a150d54d5c9e950ed41b434678f302698ad4638693ac9166ad186e4bb945"},linuxx64:{path:"cloudflared-linux-amd64",sha256:"991dffd8889ee9f0147b6b48933da9e4407e68ea8c6d984f55fa2d3db4bb431d"}},Ed=_t.tmpdir(),RR=_t.platform()==="win32"?"cloudflared.exe":"cloudflared",pc=Id.join(Ed,RR),Sd=6e4,xR=500,dc=null,Ti=null,CR=async(s,e)=>{let t=`http://localhost:${e}/metrics`,r=new Promise((o,a)=>{s.on("error",c=>{let l=`Cloudflare tunnel process error: ${c.message}`;uc.error(l,{error:c}),a(new Error(l))}),s.on("exit",c=>{if(c!==0){let l=`Cloudflare tunnel exited with code ${c}`;uc.error(l,{code:c}),a(new Error(l))}})}),n=async()=>{for(;;){try{let c=(await(await fetch(t)).text()).match(/cloudflared_tunnel_ha_connections\s+(\d+)/);if(c&&Number(c[1])>=1)return}catch{}await ie(xR)}},i=ie(Sd).then(()=>{let o=`Cloudflare tunnel connection timeout after ${Sd} seconds`;throw uc.error(o,{timeout:Sd}),new Error(o)});await Promise.race([n(),r,i])},AR=async()=>{if(await Te(pc))return;let e=IR[_t.platform()+_t.arch()];if(!e){let r=`tunnel on ${_t.platform()+_t.arch()} platform is not supported.`;throw uc.error(r,{platform:_t.platform()+_t.arch()}),new Error(r)}let t=e.extract?Id.join(Ed,e.path):pc;await Qe(`${ER}/${e.path}`,t),await qc(t,e.sha256),e.extract&&await Vc(t,Ed),await Rd.promises.chmod(pc,"755")},HT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Yp(s.company.companyId,t),AR()]);dc=r._id;let n=await VT.getPortPromise({port:9e3});Ti=GT.spawn(pc,["--metrics",`localhost:${n}`,"tunnel","--no-autoupdate","run","--protocol","http2","--token",r.token],{stdio:["ignore","pipe","pipe"]}),await CR(Ti,n),await Qp(s.company.companyId,dc),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Rd.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},qT=async s=>{let e=[];return dc&&e.push(Zp(s.company.companyId,dc)),Ti&&e.push(new Promise((t,r)=>{Ti.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Ti.kill()})),await Promise.all(e)}});var Ad={};z(Ad,{connect:()=>mc,disconnect:()=>fc,serveTunneling:()=>kR});var KT,Cd,JT,yt,xd,mc,fc,kR,Pd=I(()=>{"use strict";WT();Fn();zT();me();mt();KT=R(require("ora"));W();ae();jo();Cd=A("tunnel"),JT=s=>{var e;return[N.TESTIM_LAMBDATEST,N.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"&&s.gridData.tunnelUser&&s.gridData.tunnelUser.length>0&&s.gridData.tunnelKey&&s.gridData.tunnelKey.length>0},yt=(s,e,t)=>{var r,n,i;return Cd.info(`${t} tunnel, status: ${s}`,{companyId:(r=e.company)==null?void 0:r.companyId,projectId:(n=e.projectData)==null?void 0:n.projectId,testId:e.testId,desiredTunnel:(i=e.gridData)==null?void 0:i.tunnel,actualTunnel:t})},mc=async s=>{var r;if(!s.tunnel)return;let e;xd=O.flags.useNgrokTunnel.isEnabled({projectId:(r=s.projectData)==null?void 0:r.projectId});let t=null;try{if(e=(0,KT.default)("Starting tunnel...").start(),JT(s))t="lambdatest",yt("connecting",s,t),await ce.connectTunnel(s),yt("connected",s,t);else if(xd){t="ngrok",yt("connecting",s,t);let n=Pr();await jT(s,n),yt("connected",s,t)}else t="cloudflare",yt("connecting",s,t),await HT(s),yt("connected",s,t);e.succeed()}catch(n){let i="Failed to start tunnel. Please contact support@testim.io";throw n.isInvalidCredsForLT&&(i="Could not connect to LambdaTest. Check your credentials and then try again."),Cd.error("Failed to open tunnel",{err:n}),e==null||e.fail(i),new Error(n.isInvalidCredsForLT?`${i}
410
- ${n.stdoutResult}`:i)}},fc=async s=>{if(!s.tunnel)return;let e=null;try{JT(s)?(e="lambdatest",yt("disconnecting",s,e),await ce.disconnectTunnel(s),yt("disconnected",s,e)):xd?(e="ngrok",yt("disconnecting",s,e),await $T(s),yt("disconnected",s,e)):(e="cloudflare",yt("disconnecting",s,e),await qT(s),yt("disconnected",s,e))}catch(t){let r="catch error - failed to close tunnel";throw Cd.error(r,{err:t}),new Error(r)}},kR=async(s,e=new Promise(()=>{}))=>(await mc(s),ws(()=>fc(s)),await e)});var ZT={};z(ZT,{init:()=>tx,run:()=>YR});async function _R(s){let e=s.project,t=await Jp(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"),gs(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Zs}function DR(s,e){var i,o,a,c,l,d,m,u,f,h,g,y,w;let t=zi(e.activePlan),r=s.parallel;if(t==="free"&&r>YT)throw new x(`The free plan allows only ${YT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let S=(i=s.projectData)!=null&&i.type?LR[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&S?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[S]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
408
+ `))},yd=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:lc,argv:Td,exit:gd,cwd:Pt}=global.process,OT={development:{usw2:{servicesUrl:"https://services.dev.testim.io"},euc1:{servicesUrl:"https://services.dev.eu.testim.io"}},staging:{usw2:{servicesUrl:"https://services.staging.testim.io"},euc1:{servicesUrl:"https://services.staging.eu.testim.io"}},production:{usw2:{servicesUrl:"https://services.testim.io"},euc1:{servicesUrl:"https://services.eu.testim.io"}}},hR=async s=>{let e=Ss(s),t=await os(Qr.CACHE_FN_NAME);if(t&&t.region===e){Ys(t.servicesUrl);return}let n=(OT[Js]||OT.production)[e]||{servicesUrl:"https://services.testim.io"};lc.SERVICES_HOST||Ys(n.servicesUrl)},yR=new Set(["trace","debug","info","warn","error","silent"]);el(Td,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));bd.description("Testim.io CLI").option("-h --help","output usage information",MT).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-data [test-data]","test data file name to include in the test run").option("--test-config [test-config]","test config name to override for all tests in current execution",Ue,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Ue,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Ue,[]).option("--test-id [test-id]","test ID to run",Ue,[]).option("-l, --label [label]","labels to search test by",Ue,[]).option("-n, --name [test-name]","test name to run",Ue,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",fR).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Ue,[]).option("--test-plan-id [test-plan-id]","test plan to run",Ue,[]).option("--suite [suite-name]","suite to run",Ue,[]).option("--suite-id [suite-id]","suite ID to run",Ue,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",Ue,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(lc.TESTIM_TEST_START_TIMEOUT)||2*60*1e3).option("--timeout [test-timeout]","Test run timeout in milliseconds",Number).option("--browser-timeout [open-browser-timeout]","Get browser from grid timeout in milliseconds",Number).option("--new-browser-wait-timeout [max-wait-to-browser]","Maximum get browser wait in minutes",Number).option("--get-browser-timeout [get-browser-timeout]","Timeout for a single attempt to get browser from the grid configured in the project's plan",Number).option("--get-browser-retries [get-browser-retries]","Number of attempts to get browser from the grid configured in the project's plan",Number).option("--get-session-timeout [get-session-timeout]",'Timeout for "/session" request to the selenium server',Number,(0,hd.default)("90s")).option("--get-session-retries [get-session-retries]",'Retries for "/session" request to the selenium server',Number,3).option("--driver-request-timeout [driver-request-timeout]","Timeout for any WebDriver request to the grid server",Number,(0,hd.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).option("--local-tma-url [local-tma-url]","use a local TMA instance for appium session").option("--use-local-chrome-driver [use-local-chrome-driver]","use a local ChromeDriver instance instead of a selenium grid").option("--chrome-binary-location [chrome-binary-location]","Chrome binary location").option("--use-chrome-launcher","use a local Chrome installation without selenium").option("-mnh --mock-network-har","use the HAR file configured in the Testim editor to mock network traffic").option("-mnp --mock-network-pattern [local file location path]","use a JSON rule file to mock network traffic (Rule file schema: https://help.testim.io/page/mocking-network-traffic)").option("-omf --override-mapping-file [local file location path]","pass map file location to override mock network (see schema: https://help.testim.io/page/mocking-network-traffic)").option("-dmn --disable-mock-network","Disable mock mode for the entire CLI run").option("--run-quarantined-tests","Run quarantine tests").option("--collect-code-coverage","collect code coverage for all js files under base url").option("--code-coverage-url-filter [url pattern]","collect code coverage for all js files matching url filter (url including asterisk)").option("--code-coverage-report-path [path]","where to save coverage report (default ./coverage)").option("--code-coverage-source-map-path [path]","path of source code").option("--code-coverage-reporter [reporter]",`set code coverage reporter (default html and text), options: ${yd.join("/")}`,Ue,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Ue,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--sealights-lab-id [sealights-lab-id]","SeaLight Lab ID").option("--sealights-build-session-id [sealights-build-session-id]","SeaLight Session Build ID").option("--sealights-test-stage [sealights-test-stage]","SeaLight Test Stage Name").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Ue,[]).option("--label-intersection-operand [operand]",'Run only tests that match either all the labels with the "AND" operand, or at least one of the labels with the "OR" operand',mR("--label-intersection-operand")).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",Ue,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",Ue,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").option("--custom-capabilities-name <name>","name of pre-created custom capabilities item").option("--custom-capabilities-file <path>","path to a JSON file with capabilities settings").parse(Td);p=bd.opts(),bR=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},TR=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},_T=s=>{var r;if(!O.flags.secrets.isEnabled({projectId:p.project}))return;let t=cc.readFileSync(s);(r=ld)!=null&&r.containsSecrets(t.toString())&&ld.injectProxySecretsStoreToGlobal()},wR=async()=>{var S,b,v,T,C,_,B,G;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={},n;if(!Td.slice(2).length)throw MT(),new zr;if(p.version){let E="Testim CLI Version: ";lc.npm_package_version&&(console.log(E,lc.npm_package_version),gd(0));let k=ot();k&&(console.log(E,k),gd(0)),console.log("Could not find version, please check the package.json manually"),gd(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&of(),p.clearFileCache&&as();let i=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(i){let E=_e.resolve(i);sf(E)}if(p.usePrefechedData&&af(),p.playerRequirePath){let E=_e.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",E);let k=_e.join(E,"tsconfig.node.json"),j=require("ts-node").register({project:k,ignore:[/node_modules/,new RegExp(`^${kt.escapeRegExp(_e.relative(Pt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:j.config.options.paths,baseUrl:j.config.options.baseUrl}),(Se(),Ke(dr)).options.playerPath=E;let K=require("node:module"),q=K.prototype.require;K.prototype.require=function(ge){return ge==="rox-alias"?q.call(this,"rox-node"):ge==="canvas"?{}:q.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=cc.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new x("missing --proxy option");if(ST(p))return ET(p);try{let E={};p.configFile?(_T(p.configFile),E=require(_e.join(Pt(),p.configFile)).config):p.optionsFile&&(E=require(_e.join(Pt(),p.optionsFile))),E&&typeof E.then=="function"&&(E=await E),Object.keys(E).forEach(k=>{let D=dR(k);p[D]=gR(p[D],E[k])})}catch(E){throw E.message=`Unable to read options file: ${E.message}`,E}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((S=p.testConfig)==null?void 0:S.length)||((b=p.testConfigId)==null?void 0:b.length),a=((v=p.testPlan)==null?void 0:v.length)||((T=p.testPlanId)==null?void 0:T.length),c=((C=p.suite)==null?void 0:C.length)||((_=p.suiteId)==null?void 0:_.length);if(p.customCapabilitiesFile&&p.customCapabilitiesName)throw new x("You can either use --custom-capabilities-name or --custom-capabilities-file");if((p.customCapabilitiesFile||p.customCapabilitiesName)&&(p.browserstackOptions||p.sauceOptions||p.seleniumCapsFile||p.perfectoOptions))throw new x("Custom capabilities parameters can't be used together with --browserstack-options, --sauce-options, --selenium-caps-file or --perfecto-options parameters");if(p.customCapabilitiesFile)try{n=require(_e.join(Pt(),p.customCapabilitiesFile)),$o(n)}catch(E){throw E instanceof x?E:new x(`Failed to parse custom capabilities file: ${E.message}`)}if(p.seleniumCapsFile){bi("--selenium-caps-file","--custom-capabilities-name or --custom-capabilities-file");try{r=require(_e.join(Pt(),p.seleniumCapsFile))}catch(E){throw new x(`Failed to parse selenium caps file file error: ${E.message}`)}}if((B=p.reporters)!=null&&B.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new x("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new x("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new x("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(_e.join(Pt(),p.chromeExtraPrefs))}catch(E){throw new x(`Failed to read/open chrome extra prefs file error: ${E.message}`)}if(p.chromeExtraArgs){let E=p.chromeExtraArgs.split(",");for(let k of E){let[D]=k.split("=");kT.includes(D)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(k),D==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${D}), allowed values: ${JSON.stringify(kT)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&_T(p.paramsFile),s={...s,...require(_e.join(Pt(),p.paramsFile))}}catch(E){throw new x(`Failed to read/open params file error: ${E.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(E){throw new x(`Failed to parse params string error: ${E.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new x("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(bR(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions){bi("--sauce-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(_e.join(Pt(),p.sauceOptions)),k=E.platformName&&["ios","android"].includes(E.platformName.toLowerCase());if(E.browserName){let j=E.browserName.toLowerCase();switch(j){case"microsoftedge":p.browser="edge";break;default:p.browser=j}}p.browser==="edge"&&parseFloat(E.version)>=79&&(p.browser="edge-chromium");let D=parseFloat(E.version)<50&&!["dev","beta"].includes(E.version);if(!k&&p.browser==="chrome"&&D)throw new x("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...E}}catch(E){throw new x(`Failed to parse saucelabs options file error: ${E.message}`)}}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new x("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(TR(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions){bi("--browserstack-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(_e.join(Pt(),p.browserstackOptions)),k=E.platform&&["mac","android"].includes(E.platform.toLowerCase());if(E.browserName&&(p.browser=E.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(E.browser_version)>=79&&(p.browser="edge-chromium"),!k&&parseFloat(E.browser_version)<50&&p.browser==="chrome")throw new x("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...E}}catch(E){throw new x(`Failed to parse browserstack options file error: ${E.message}`)}}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions){bi("--perfecto-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(_e.join(Pt(),p.perfectoOptions)),k={location:"US East",securityToken:p.perfectoToken};p.perfecto={...k,...E}}catch(E){throw new x(`Failed to parse perfecto options file error: ${E.message}`)}}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let E=require(_e.join(Pt(),p.testobjectOptions)),k={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...k,...E}}catch(E){throw new x(`Failed to parse test object options file error: ${E.message}`)}let l={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId,testStage:p.sealightsTestStage}};if(p.testOptimization=l,!p.project){let k=await(await Promise.resolve().then(()=>(ac(),fd))).getProjectId();if(k)p.project=k;else throw new x("missing project-id info, either --login to provide new credentials or use --project <project-id>")}hR(p.project),O.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=Math.max(p.browserTimeout,p.getSessionTimeout),p.driverRequestTimeout=Math.max(p.browserTimeout,p.driverRequestTimeout);let m=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let k=await(await Promise.resolve().then(()=>(ac(),fd))).getToken();if(k)p.token=k;else throw new x("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let u=E=>E<=0||!Number.isInteger(E);if(u(p.retries))throw new x("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new x("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(u(p.browserTimeout))throw new x("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(u(p.newBrowserWaitTimeout))throw new x("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(u(p.timeout))throw new x("test run timeout could not be a negative number, --timeout <run-timeout>");if(u(p.beforeParallel))throw new x("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(u(p.parallel))throw new x("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(u(p.afterParallel))throw new x("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![J.EXTENSION,J.SELENIUM,J.APPIUM].includes(p.mode))throw new x(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Br,...ei].includes(p.browser))throw new x(`browser ${p.browser} is not supported`);if(p.mode!==J.SELENIUM&&p.disableNativeEvents)throw new x("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!yR.has(p.appiumLogLevel))throw new x(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new x("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||c||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new x("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!a&&(p.beforeParallel!==1||p.afterParallel!==1))throw new x("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new x("please define exactly one of --grid or --grid-id or --host");if((G=p.host)!=null&&G.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=DT.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(k=>k.trim()).filter(Boolean);let E=p.resultLabel.filter(k=>k.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&Ir()&&p.resultLabel.unshift(Ir()),E.length)throw new x("A result label cannot exceed 250 characters")}let h=Fo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new x("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new x("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new x("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(c||p.name.length||p.testId.length||p.label.length||a))throw new x("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!kt.inRange(kt.parseInt(p.setRetention),1,11))throw new x("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let g="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new x(`--mock-network-har ${g}`);if(p.mockNetworkPattern)throw new x(`--mock-network-pattern ${g}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new x("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new x("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new x("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new x("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&kt.difference(p.codeCoverageReporter,yd).length){let E=kt.difference(p.codeCoverageReporter,yd);throw new x(`invalid --code-coverage-reporter parameters ${E.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let y={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},w=Object.keys(y).filter(E=>Boolean(p[E]));if([J.APPIUM,J.SELENIUM].includes(p.mode)&&w.length){let E=w.length>1?"are":"is";throw new x(`${w.map(k=>y[k]).join(" and ")} ${E} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let E=cc.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(E)}catch(E){throw new x(`failed to parse field file error: ${E.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new x("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.labelIntersectionOperand===!0)throw new x("The --label-intersection-operand flag requires a value. Please provide a value after the flag.");if(p.labelIntersectionOperand&&!Object.values(on).includes(p.labelIntersectionOperand))throw new x(`The --label-intersection-operand flag must be one of the following values: ${Object.values(on).join(", ")}`);if(p.labelIntersectionOperand&&kt.isEmpty(p.intersectWithLabel))throw new x("The --label-intersection-operand flag must be used together with the --intersect-with-label flag.");if(p.highSpeed&&(bi("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new x("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new x("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new x("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let E={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},k=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...E,...k}}catch(E){throw new x(`failed to parse lightweightMode settings error: ${E.message}`)}else p.turboMode&&![J.APPIUM,J.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[J.APPIUM,J.SELENIUM].includes(p.mode)&&console.warn(`
409
+ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new x("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?Ir():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,testOptimization:p.testOptimization,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionPath:p.extensionPath,extensionLocation:[p.extensionPath].filter(Boolean),playerLocation:p.playerPath||h,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:m,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections,labelIntersectionOperand:p.labelIntersectionOperand},testDataFileName:p.testData,downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps,customCapabilities:n,customCapabilitiesName:p.customCapabilitiesName}}});var wd,vR,Gs,BT,jT,vd,$T,WT=I(()=>{"use strict";F();Q();W();ws();wd=A("testimNgrok"),vR=".whitelisted-ngrok.testim.io",Gs="",jT=async(s,e={})=>{if(!e.ngrokToken)throw new x("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${ne()}-${s.projectData.projectId}${vR}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let i=await(await Fe("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(wd.info("replace https to http"),Gs=i.replace("https://","http://")):Gs=i,s.tunnelDiagnostics&&vd(),s.baseUrl=Gs},vd=async(s=!0)=>{try{let t=(await Fe("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===Gs);console.log("ngrok stats",n),wd.info("ngrok stats",{tunnel:n})}catch(e){wd.error("error collecting ngrok stats",{err:e})}s&&(BT=setTimeout(()=>vd(),1e4))},$T=async s=>{if(!Gs)return;clearTimeout(BT),s.tunnelDiagnostics&&await vd(!1),await(await Fe("ngrok")).disconnect(Gs)}});var Ot,Id,VT,Rd,GT,uc,ER,IR,Ed,RR,pc,Sd,xR,dc,Ti,CR,AR,HT,qT,zT=I(()=>{"use strict";Ot=R(require("node:os")),Id=R(require("node:path")),VT=R(require("portfinder")),Rd=R(require("node:fs")),GT=R(require("node:child_process"));F();ye();W();uc=A("testimCloudflare"),ER="https://github.com/cloudflare/cloudflared/releases/download/2025.11.1/",IR={win32ia32:{path:"cloudflared-windows-386.exe",sha256:"1e76c0d4e6ff2576db46ad1a7397415729fbaf886b22aa49327f66185a2e8fc8"},win32x64:{path:"cloudflared-windows-amd64.exe",sha256:"413f9b24dc6e61a455564651524f167b8ce29ac4ccd40703dea7af93cd37ed39"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",sha256:"155a288fef19dba08f0c7145c16a207baf137462d8a1289a78bf8564f9e51244",extract:!0},darwinarm64:{path:"cloudflared-darwin-arm64.tgz",sha256:"45cfbb59a720f60b873906aa6469f8c4058f26be6d351c3e2920bc9cb4714273",extract:!0},linuxia32:{path:"cloudflared-linux-386",sha256:"bec7a150d54d5c9e950ed41b434678f302698ad4638693ac9166ad186e4bb945"},linuxx64:{path:"cloudflared-linux-amd64",sha256:"991dffd8889ee9f0147b6b48933da9e4407e68ea8c6d984f55fa2d3db4bb431d"}},Ed=Ot.tmpdir(),RR=Ot.platform()==="win32"?"cloudflared.exe":"cloudflared",pc=Id.join(Ed,RR),Sd=6e4,xR=500,dc=null,Ti=null,CR=async(s,e)=>{let t=`http://localhost:${e}/metrics`,r=new Promise((o,a)=>{s.on("error",c=>{let l=`Cloudflare tunnel process error: ${c.message}`;uc.error(l,{error:c}),a(new Error(l))}),s.on("exit",c=>{if(c!==0){let l=`Cloudflare tunnel exited with code ${c}`;uc.error(l,{code:c}),a(new Error(l))}})}),n=async()=>{for(;;){try{let c=(await(await fetch(t)).text()).match(/cloudflared_tunnel_ha_connections\s+(\d+)/);if(c&&Number(c[1])>=1)return}catch{}await ie(xR)}},i=ie(Sd).then(()=>{let o=`Cloudflare tunnel connection timeout after ${Sd} seconds`;throw uc.error(o,{timeout:Sd}),new Error(o)});await Promise.race([n(),r,i])},AR=async()=>{if(await Te(pc))return;let e=IR[Ot.platform()+Ot.arch()];if(!e){let r=`tunnel on ${Ot.platform()+Ot.arch()} platform is not supported.`;throw uc.error(r,{platform:Ot.platform()+Ot.arch()}),new Error(r)}let t=e.extract?Id.join(Ed,e.path):pc;await Ye(`${ER}/${e.path}`,t),await qc(t,e.sha256),e.extract&&await Vc(t,Ed),await Rd.promises.chmod(pc,"755")},HT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Yp(s.company.companyId,t),AR()]);dc=r._id;let n=await VT.getPortPromise({port:9e3});Ti=GT.spawn(pc,["--metrics",`localhost:${n}`,"tunnel","--no-autoupdate","run","--protocol","http2","--token",r.token],{stdio:["ignore","pipe","pipe"]}),await CR(Ti,n),await Qp(s.company.companyId,dc),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Rd.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},qT=async s=>{let e=[];return dc&&e.push(Zp(s.company.companyId,dc)),Ti&&e.push(new Promise((t,r)=>{Ti.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Ti.kill()})),await Promise.all(e)}});var Ad={};z(Ad,{connect:()=>mc,disconnect:()=>fc,serveTunneling:()=>kR});var KT,Cd,JT,ht,xd,mc,fc,kR,Pd=I(()=>{"use strict";WT();Mn();zT();me();dt();KT=R(require("ora"));W();ae();jo();Cd=A("tunnel"),JT=s=>{var e;return[N.TESTIM_LAMBDATEST,N.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"&&s.gridData.tunnelUser&&s.gridData.tunnelUser.length>0&&s.gridData.tunnelKey&&s.gridData.tunnelKey.length>0},ht=(s,e,t)=>{var r,n,i;return Cd.info(`${t} tunnel, status: ${s}`,{companyId:(r=e.company)==null?void 0:r.companyId,projectId:(n=e.projectData)==null?void 0:n.projectId,testId:e.testId,desiredTunnel:(i=e.gridData)==null?void 0:i.tunnel,actualTunnel:t})},mc=async s=>{var r;if(!s.tunnel)return;let e;xd=O.flags.useNgrokTunnel.isEnabled({projectId:(r=s.projectData)==null?void 0:r.projectId});let t=null;try{if(e=(0,KT.default)("Starting tunnel...").start(),JT(s))t="lambdatest",ht("connecting",s,t),await ce.connectTunnel(s),ht("connected",s,t);else if(xd){t="ngrok",ht("connecting",s,t);let n=Ar();await jT(s,n),ht("connected",s,t)}else t="cloudflare",ht("connecting",s,t),await HT(s),ht("connected",s,t);e.succeed()}catch(n){let i="Failed to start tunnel. Please contact support@testim.io";throw n.isInvalidCredsForLT&&(i="Could not connect to LambdaTest. Check your credentials and then try again."),Cd.error("Failed to open tunnel",{err:n}),e==null||e.fail(i),new Error(n.isInvalidCredsForLT?`${i}
410
+ ${n.stdoutResult}`:i)}},fc=async s=>{if(!s.tunnel)return;let e=null;try{JT(s)?(e="lambdatest",ht("disconnecting",s,e),await ce.disconnectTunnel(s),ht("disconnected",s,e)):xd?(e="ngrok",ht("disconnecting",s,e),await $T(s),ht("disconnected",s,e)):(e="cloudflare",ht("disconnecting",s,e),await qT(s),ht("disconnected",s,e))}catch(t){let r="catch error - failed to close tunnel";throw Cd.error(r,{err:t}),new Error(r)}},kR=async(s,e=new Promise(()=>{}))=>(await mc(s),bs(()=>fc(s)),await e)});var ZT={};z(ZT,{init:()=>tx,run:()=>YR});async function _R(s){let e=s.project,t=await Jp(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"),ms(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Qs}function DR(s,e){var i,o,a,c,l,d,m,u,f,h,g,y,w;let t=zi(e.activePlan),r=s.parallel;if(t==="free"&&r>YT)throw new x(`The free plan allows only ${YT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let S=(i=s.projectData)!=null&&i.type?LR[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&S?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[S]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
411
411
  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 v=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.tunnel;if(s.tunnel&&!v)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 T=(m=(d=e.activePlan)==null?void 0:d.premiumFeatures)==null?void 0:m.runInTurboMode;s.lightweightMode&&!T&&(console.warn(`
412
- 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)===N.TESTIM_TVC){let S=e.tvcLicense.expireAt||1;if(Date.now()>S&&!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)===N.TESTIM_TDC){let S=e.tdcLicense.expireAt||1;if(Date.now()>S)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 S=(w=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:w.resultRetention;if(n>S)throw new x(`Retention days (${n}) cannot be greater than the company's retention days (${S}). Run aborted`)}if(ir(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let S=e.tvcLicense,b=e.tdcLicense;if(S!=null&&S.isPaid||b!=null&&b.isPaid)return;let v=e==null?void 0:e.createdAt;if(new Date(v)<new Date(O.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 C=s.retries;C&&C>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function NR(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await _R(s)}catch(t){if([x,Zs].some(r=>t instanceof r))throw t;kd.error("could not validate cli account",{err:t})}}function MR(s){let e=Pr();return Kf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function FR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(O.flags.useNewWSCLI.isEnabled()&&!e&&!t)return xt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Yo(),Gh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Qo(),zh));r.init(s)}}function UR(s,e){let{branch:t,autoDetect:r}=s;if(Hf(e,r),!e&&!r)throw new x(`branch ${t} does not exist, run aborted.`)}async function BR(s,e){let{id:t,type:r}=e,i=QT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=Pn();i&&(s.sfdcCredential=await Kp({projectId:t,branch:o}))}async function jR(s){if(!s.testDataFileName)return;let{testDataFileName:e}=s,t;try{t=(await zp(`fileName=${e}&action=download&fileType=test-data&projectId=${s.project}`)).s3Url;let i=await(await fetch(t)).json();gt("test-data-file-used-in-cli",{projectId:s.project,testDataFileId:e,source:s.source}),s.testDataFileName=e,s.testDataString=i.testData}catch(r){let n=t?`, s3Url: ${t}`:"";throw new x(`Failed to read/open test data file error: ${r.message}${n}`)}}function $R(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=zi(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<XT?XT:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(i),O.setIsStartUp(o),O.setPlanType(a),Ut.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function WR(s,e){s.editorUrl=ot||e}function VR(s,e){s.allGrids=e}function GR(s,e){s.authData=e}function HR(s,e){let{id:t,name:r,type:n,defaults:i}=e;O.setProjectId(t),O.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function qR(s){var e;s.gridData=await Wf(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function zR(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function KR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(gt("user-override-file",t),s.mockNetworkRules=await yT(s.overrideMappingFile))}async function JR(s){if(s.customCapabilitiesName){let e=await td(s.project,s.customCapabilitiesName);if(!e)throw new x(`"${s.customCapabilitiesName}" custom capabilities not found`);s.customCapabilities=e.capabilities}}async function XR(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await NR(s),M("in runRunner before tunnel.connect"),await mc(s),M("in runRunner after tunnel.connect");let a=await new zr(e).run(s);return M("before tunnel.disconnect"),await fc(s),await ex(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function QR(s){var e;Ut.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
412
+ 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)===N.TESTIM_TVC){let S=e.tvcLicense.expireAt||1;if(Date.now()>S&&!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)===N.TESTIM_TDC){let S=e.tdcLicense.expireAt||1;if(Date.now()>S)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 S=(w=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:w.resultRetention;if(n>S)throw new x(`Retention days (${n}) cannot be greater than the company's retention days (${S}). Run aborted`)}if(ir(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let S=e.tvcLicense,b=e.tdcLicense;if(S!=null&&S.isPaid||b!=null&&b.isPaid)return;let v=e==null?void 0:e.createdAt;if(new Date(v)<new Date(O.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 C=s.retries;C&&C>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function NR(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await _R(s)}catch(t){if([x,Qs].some(r=>t instanceof r))throw t;kd.error("could not validate cli account",{err:t})}}function MR(s){let e=Ar();return Kf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function FR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(O.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Rt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Yo(),Gh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Qo(),zh));r.init(s)}}function UR(s,e){let{branch:t,autoDetect:r}=s;if(Hf(e,r),!e&&!r)throw new x(`branch ${t} does not exist, run aborted.`)}async function BR(s,e){let{id:t,type:r}=e,i=QT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=An();i&&(s.sfdcCredential=await Kp({projectId:t,branch:o}))}async function jR(s){if(!s.testDataFileName)return;let{testDataFileName:e}=s,t;try{t=(await zp(`fileName=${e}&action=download&fileType=test-data&projectId=${s.project}`)).s3Url;let i=await(await fetch(t)).json();ft("test-data-file-used-in-cli",{projectId:s.project,testDataFileId:e,source:s.source}),s.testDataFileName=e,s.testDataString=i.testData}catch(r){let n=t?`, s3Url: ${t}`:"";throw new x(`Failed to read/open test data file error: ${r.message}${n}`)}}function $R(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=zi(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<XT?XT:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(i),O.setIsStartUp(o),O.setPlanType(a),Ft.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function WR(s,e){s.editorUrl=it||e}function VR(s,e){s.allGrids=e}function GR(s,e){s.authData=e}function HR(s,e){let{id:t,name:r,type:n,defaults:i}=e;O.setProjectId(t),O.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function qR(s){var e;s.gridData=await Wf(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function zR(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function KR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(ft("user-override-file",t),s.mockNetworkRules=await yT(s.overrideMappingFile))}async function JR(s){if(s.customCapabilitiesName){let e=await td(s.project,s.customCapabilitiesName);if(!e)throw new x(`"${s.customCapabilitiesName}" custom capabilities not found`);s.customCapabilities=e.capabilities}}async function XR(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await NR(s),M("in runRunner before tunnel.connect"),await mc(s),M("in runRunner after tunnel.connect");let a=await new Hr(e).run(s);return M("before tunnel.disconnect"),await fc(s),await ex(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function QR(s){var e;Ft.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
413
413
  \x1B[4m\x1B[36mOur Free grid offers basic service performance.
414
414
  If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
415
- `)}function ZR(s,e,t){s==="redis"&&Dn.start(t,e),s==="mongo"&&Cn.start(e)}async function ex(s,e,t){s==="redis"&&await Dn.end(t,e),s==="mongo"&&await Cn.end(e)}async function tx(s){var h,g,y,w,S,b;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=FR(e,{disableResults:i||Boolean((t==null?void 0:t.disableResults)&&(r||n===J.SELENIUM)),disableRemoteStep:i||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,companyByProjectId:c,projectById:l,branchName:d,allGrids:m,clientConfig:u}=await yi(s);if(c.disabled)throw new x("The company is disabled.");if(l.disabled)throw new x("The project is disabled.");if(s.printGrids){let v=m.sort((T,C)=>T.type.localeCompare(C.type));console.table(v.reduce((T,C)=>{class _{constructor(E,k){this.Type=E,this.Browsers=k}}let B=Object.entries(C.browsers||{"N/A":""}).map(G=>G.join(":")).join(", ");return T[C.name]=new _(C.type,B),T},{})),process.exit(0)}if(await o,M("after featureFlagsReady and socketConnected"),WR(s,u.editorUrl),$R(s,c),HR(s,l),zR(s,l),UR(s,d),VR(s,m),GR(s,a),await jR(s),await BR(s,l),await qR(s),await JR(s),DR(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[Wg(s)]),O.flags.clearRunnerFileCache.isEnabled())try{await ls(),kd.info("runner file cache cleared")}catch(v){kd.error("failed to clear runner file cache",{err:v})}(g=s.lightweightMode)!=null&&g.disableLabs||await Jn.loadLabFeatures(l.id,c.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(O.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((w=s.lightweightMode)==null?void 0:w.type)==="turboMode"&&console.log(`
416
- Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),ZR(s.slotService,e,c.id),MR(e),await KR(s),QR(s);let f=Pn();await Z.setOptions(s,f),(b=(S=s.testOptimization)==null?void 0:S.seaLights)!=null&&b.testStage&&s.testOptimization.seaLights.testStage!==OR&&gs(a.uid,"cli-sealights_stage_changed",{testStage:s.testOptimization.seaLights.testStage,projectId:e})}var QT,XT,YT,OR,kd,LR,YR,ew=I(()=>{"use strict";QT=R(require("lodash"));F();Pd();Ve();fs();Ts();kr();Fl();ye();mt();Jt();W();Bt();le();ae();Q();jp();Jo();Ou();me();_n();id();Vn();XT=30*60*1e3,YT=1,OR="Testim Automation",kd=A("runner");LR={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};YR=XR});function tw(s){s.get("/",(e,t)=>{let r=Od();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:sc()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());md({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var rw=I(()=>{"use strict";ac();_d();rd()});var Ld,sw,yr,gc,nw=I(()=>{"use strict";Ld=R(require("chalk"));Os();sw=require("express");W();Q();ol();yr=A("cli-router"),gc=(0,sw.Router)();gc.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}if(n.nodePackageParams){let u=n.nodePackageParams.map(h=>h.testimPackageLocalLocation).filter(Boolean),f=il(u);if(f){yr.error("Invalid package paths detected",{invalidPaths:f,stepId:r,testResultId:o}),e.status(400).json({success:!1,code:"invalid-package-path",message:`Invalid package path(s) detected: ${f.join(", ")}`});return}}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d,nodePackageParams:n.nodePackageParams};try{let u=await ks(t,r,n,i,o,a,c,l,d);u.success||(console.log(Ld.default.red(u.result.resultValue)),yr.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){yr.error("failed to run cli code",{err:u,...m}),console.log(Ld.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});gc.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:i,stepResultId:o,timeout:a}=s.body;if(!t||typeof i!="object"||!r||typeof n!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let c=nl(i);if(c){yr.error("Invalid package names detected",{invalidNames:c,stepId:t,testResultId:r}),e.status(400).json({success:!1,code:"invalid-package-name",message:`Invalid package name(s): ${c.join(", ")}`});return}let l={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let d=await Ps(t,r,n,i,o,a);yr.info("installed packages successfully",l),e.status(200).json({success:!0,data:d})}catch(d){if(d instanceof Nt){yr.error("failed to install node packages",{err:d,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:d.message});return}if(d instanceof ue){yr.error("timeout installing node package",{err:d,...l}),e.status(200).json({success:!1,code:"timeout"});return}yr.error("failed to install node packages",{err:d,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var iw=I(()=>{"use strict";nw()});var lw={};z(lw,{orchestrateRoutes:()=>rx});function rx(s){let e=(0,aw.default)();e.disable("x-powered-by"),s(e),e.use(Dd.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,cw.default)()),e.use(Dd.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:Ge||Hd?"*":["chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia"]};return e.use("*",(0,ow.default)(r)),tw(e),e.use("/cliJs",gc),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var ow,aw,Dd,cw,uw=I(()=>{"use strict";ow=R(require("cors")),aw=R(require("express")),Dd=R(require("body-parser")),cw=R(require("compression"));rw();iw();le()});var dw={};z(dw,{init:()=>sx});async function sx({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(uw(),lw));return new Promise((i,o)=>{let a=()=>{};t&&(Df(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let c=n(a),l=pw.createServer(c);l.listen(s,e),l.on("error",d),l.on("listening",m);function d(u){if(u.syscall!=="listen")return o(u);switch(u.code){case"EACCES":case"EPERM":return o(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new x(`Port ${s} is already in use, is another Testim instance running?`));default:return o(u)}}function m(){let{port:u}=l.address();console.log(`Running on port: ${u}`),nx()}})}async function nx(){await require("prompts")({name:"",type:"text",message:'Type the word "stop" or Press Ctrl + C.',validate:t=>t.toUpperCase().trim()==="STOP"}),console.log("Exiting Testim CLI"),process.exit(0)}var pw,mw=I(()=>{"use strict";pw=R(require("http"));mt();Q()});var ww={};z(ww,{getStartedWithStart:()=>Od,runAgentMode:()=>cx});async function cx(s){var r;let e;if(await Cr(s.playerLocation,s.canary),s.startTestimBrowser){await px();try{e=await ux(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new x('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(mw(),dw));return e!=null&&e.webdriverApi&&setTimeout(()=>{setTimeout(()=>(fp(),Je(Pb)))},6e3),t.init(s)}function Od(){return bw}function fw(s){try{return process.kill(s,0)}catch{return!1}}async function lx(s,e,t){let r=br.join(St,`chrome-${vn}-process`),n=3e3,i=()=>{Le.rmSync(r,{recursive:!0}),console.log(`
415
+ `)}function ZR(s,e,t){s==="redis"&&Ln.start(t,e),s==="mongo"&&xn.start(e)}async function ex(s,e,t){s==="redis"&&await Ln.end(t,e),s==="mongo"&&await xn.end(e)}async function tx(s){var h,g,y,w,S,b;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=FR(e,{disableResults:i||Boolean((t==null?void 0:t.disableResults)&&(r||n===J.SELENIUM)),disableRemoteStep:i||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,companyByProjectId:c,projectById:l,branchName:d,allGrids:m,clientConfig:u}=await yi(s);if(c.disabled)throw new x("The company is disabled.");if(l.disabled)throw new x("The project is disabled.");if(s.printGrids){let v=m.sort((T,C)=>T.type.localeCompare(C.type));console.table(v.reduce((T,C)=>{class _{constructor(E,k){this.Type=E,this.Browsers=k}}let B=Object.entries(C.browsers||{"N/A":""}).map(G=>G.join(":")).join(", ");return T[C.name]=new _(C.type,B),T},{})),process.exit(0)}if(await o,M("after featureFlagsReady and socketConnected"),WR(s,u.editorUrl),$R(s,c),HR(s,l),zR(s,l),UR(s,d),VR(s,m),GR(s,a),await jR(s),await BR(s,l),await qR(s),await JR(s),DR(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[Wg(s)]),O.flags.clearRunnerFileCache.isEnabled())try{await as(),kd.info("runner file cache cleared")}catch(v){kd.error("failed to clear runner file cache",{err:v})}(g=s.lightweightMode)!=null&&g.disableLabs||await Jn.loadLabFeatures(l.id,c.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(O.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((w=s.lightweightMode)==null?void 0:w.type)==="turboMode"&&console.log(`
416
+ Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),ZR(s.slotService,e,c.id),MR(e),await KR(s),QR(s);let f=An();await Z.setOptions(s,f),(b=(S=s.testOptimization)==null?void 0:S.seaLights)!=null&&b.testStage&&s.testOptimization.seaLights.testStage!==OR&&ms(a.uid,"cli-sealights_stage_changed",{testStage:s.testOptimization.seaLights.testStage,projectId:e})}var QT,XT,YT,OR,kd,LR,YR,ew=I(()=>{"use strict";QT=R(require("lodash"));F();Pd();$e();ds();ys();Pr();Fl();ye();dt();Xt();W();Ut();ue();ae();Q();jp();Jo();Ou();me();On();id();Wn();XT=30*60*1e3,YT=1,OR="Testim Automation",kd=A("runner");LR={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};YR=XR});function tw(s){s.get("/",(e,t)=>{let r=Od();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:sc()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());md({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var rw=I(()=>{"use strict";ac();_d();rd()});var Ld,sw,hr,gc,nw=I(()=>{"use strict";Ld=R(require("chalk"));ks();sw=require("express");W();Q();ol();hr=A("cli-router"),gc=(0,sw.Router)();gc.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}if(n.nodePackageParams){let u=n.nodePackageParams.map(h=>h.testimPackageLocalLocation).filter(Boolean),f=il(u);if(f){hr.error("Invalid package paths detected",{invalidPaths:f,stepId:r,testResultId:o}),e.status(400).json({success:!1,code:"invalid-package-path",message:`Invalid package path(s) detected: ${f.join(", ")}`});return}}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d,nodePackageParams:n.nodePackageParams};try{let u=await Ps(t,r,n,i,o,a,c,l,d);u.success||(console.log(Ld.default.red(u.result.resultValue)),hr.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){hr.error("failed to run cli code",{err:u,...m}),console.log(Ld.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});gc.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:i,stepResultId:o,timeout:a}=s.body;if(!t||typeof i!="object"||!r||typeof n!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let c=nl(i);if(c){hr.error("Invalid package names detected",{invalidNames:c,stepId:t,testResultId:r}),e.status(400).json({success:!1,code:"invalid-package-name",message:`Invalid package name(s): ${c.join(", ")}`});return}let l={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let d=await As(t,r,n,i,o,a);hr.info("installed packages successfully",l),e.status(200).json({success:!0,data:d})}catch(d){if(d instanceof Dt){hr.error("failed to install node packages",{err:d,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:d.message});return}if(d instanceof pe){hr.error("timeout installing node package",{err:d,...l}),e.status(200).json({success:!1,code:"timeout"});return}hr.error("failed to install node packages",{err:d,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var iw=I(()=>{"use strict";nw()});var lw={};z(lw,{orchestrateRoutes:()=>rx});function rx(s){let e=(0,aw.default)();e.disable("x-powered-by"),s(e),e.use(Dd.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,cw.default)()),e.use(Dd.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:We||Hd?"*":["chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia"]};return e.use("*",(0,ow.default)(r)),tw(e),e.use("/cliJs",gc),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var ow,aw,Dd,cw,uw=I(()=>{"use strict";ow=R(require("cors")),aw=R(require("express")),Dd=R(require("body-parser")),cw=R(require("compression"));rw();iw();ue()});var dw={};z(dw,{init:()=>sx});async function sx({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(uw(),lw));return new Promise((i,o)=>{let a=()=>{};t&&(Df(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let c=n(a),l=pw.createServer(c);l.listen(s,e),l.on("error",d),l.on("listening",m);function d(u){if(u.syscall!=="listen")return o(u);switch(u.code){case"EACCES":case"EPERM":return o(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new x(`Port ${s} is already in use, is another Testim instance running?`));default:return o(u)}}function m(){let{port:u}=l.address();console.log(`Running on port: ${u}`),nx()}})}async function nx(){await require("prompts")({name:"",type:"text",message:'Type the word "stop" or Press Ctrl + C.',validate:t=>t.toUpperCase().trim()==="STOP"}),console.log("Exiting Testim CLI"),process.exit(0)}var pw,mw=I(()=>{"use strict";pw=R(require("http"));dt();Q()});var ww={};z(ww,{getStartedWithStart:()=>Od,runAgentMode:()=>cx});async function cx(s){var r;let e;if(await xr(s.playerLocation,s.canary),s.startTestimBrowser){await px();try{e=await ux(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new x('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(mw(),dw));return e!=null&&e.webdriverApi&&setTimeout(()=>{setTimeout(()=>(fp(),Ke(Pb)))},6e3),t.init(s)}function Od(){return bw}function fw(s){try{return process.kill(s,0)}catch{return!1}}async function lx(s,e,t){let r=yr.join(vt,`chrome-${wn}-process`),n=3e3,i=()=>{Le.rmSync(r,{recursive:!0}),console.log(`
417
417
 
418
- Browser session ended`),process.exit(0)};if(await Te(r)){let f=JSON.parse(Le.readFileSync(r));if(fw(f.pid)){let h=()=>fw(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await co();await Te(qs)||await Le.promises.mkdir(qs,{recursive:!0});let c=[...Tw(qs,e,t,o).desiredCapabilities.chromeOptions.args,...yc.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],l={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=s.extensionPath?"http://localhost:3000/app/":new URL("?startMode=true",ot||vr).href,m=await yc.launch({chromeFlags:c,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:qs,chromePath:o,envVars:l}),u={port:m.port,pid:m.pid,cdpUrl:await xr(`localhost:${m.port}`)};return Le.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",i),m.process.once("close",i),{webdriverApi:u}}async function ux(s){let e=`${tr}/testim-full-master.zip`,t=br.basename(e),r=br.join(St,t),n=br.join(St,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await Te(r)){let f=await Le.promises.stat(r);i=Date.now()-ox>f.mtimeMs}if(await Le.promises.mkdir(St,{recursive:!0}),i){let f=(0,hw.default)("Downloading Testim Editor").start();await Qe(e,r);try{await Ze(r,n)}catch{await Le.promises.rm(r,{recursive:!0,force:!0}),await Qe(e,r);try{await Ze(r,n)}catch{throw await Le.promises.rm(r,{recursive:!0,force:!0}),f.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await Le.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Le.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await lx(s,o,n);await yn({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=Tw(qs,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=(Kn(),Je(Ih)),{SeleniumPerfStats:l}=(Es(),Je(Ng)),d=new c;d.seleniumPerfStats=new l;let m=await d.initClient(a);bw=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":ot||vr}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await xr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function Tw(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];t&&i.push(`--load-extension=${t}`);try{let o=Wo();o.length&&o.forEach(a=>i.push(`--disable-features=${a}`))}catch{}return{logLevel:ix,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function px(){if(await Te(hc))try{let{webSocketDebuggerUrl:s}=await dx();await mx(s),await Le.promises.unlink(hc)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Le.promises.unlink(hc)}}async function dx(){let s=await Le.promises.readFile(hc,{encoding:"utf8"}),[e,t]=s.split(`
419
- `).map(i=>i.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await xr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function mx(s,e=100){let t=await fx(s,e);return nr(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function fx(s,e=100){let t=Ja({timeout:e}),r=new yw.default(s,t),n=nr(o=>{r.once("open",o)}).then(()=>{r.removeAllListeners()}),i=nr(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return Promise.race([n,i]).then(()=>r)}var gw,hw,yw,Le,br,yc,ix,ox,qs,ax,hc,bw,_d=I(()=>{"use strict";gw=R(require("ms")),hw=R(require("ora")),yw=R(require("ws")),Le=R(require("node:fs")),br=R(require("node:path")),yc=R(require("chrome-launcher"));le();Tn();Q();Il();F();Go();Xa();ix=Oi?"verbose":"silent",ox=(0,gw.default)("1h"),qs=br.join(St,"profile"),ax="DevToolsActivePort",hc=br.join(qs,ax);bw=!1});var LM=require("source-map-support/register");var Ai=R(require("os")),Ks=R(require("url")),Js=R(require("http")),wc=R(require("https")),Si=R(require("form-data")),Ei=class{constructor(){this.onloadstart=null;this.onprogress=null;this.onabort=null;this.onerror=null;this.onload=null;this.ontimeout=null;this.onloadend=null;this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]||=[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let i of r)i==null||i.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},Ii=class extends Ei{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(t!=null)if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let i=0;i<t.byteLength;i++)r[i]=n[i];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=t.byteOffset,i=new Uint8Array(t.buffer);for(let o=0;o<t.byteLength;o++)r[o]=i[o+n];this._body=r}else if(typeof t=="object"&&t instanceof Si.default)this._body=null;else throw new Error(`Unsupported send() data ${t}`)}_finalizeHeaders(t,r){this._contentType&&!("content-type"in r)&&(t["Content-Type"]=this._contentType),this._body&&(t["Content-Length"]=this._body.length.toString())}_startUpload(t){this._body&&t.write(this._body),t.end()}},zs=class{constructor(e){this.type=e;this.target=null;this.currentTarget=null;this.lengthComputable=!1;this.loaded=0;this.total=0;this.bubbles=!1;this.cancelable=!1}},Ri=class extends Error{},xi=class extends Error{},Ci=class extends Error{},Tr=class extends Error{},Ae=class extends Ei{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Js.globalAgent;this.nodejsHttpsAgent=wc.globalAgent;this.nodejsBaseUrl=null;this._restrictedMethods={CONNECT:!0,TRACE:!0,TRACK:!0};this._restrictedHeaders={"accept-charset":!0,"accept-encoding":!0,"access-control-request-headers":!0,"access-control-request-method":!0,connection:!0,"content-length":!0,cookie:!0,cookie2:!0,date:!0,dnt:!0,expect:!0,host:!0,"keep-alive":!0,origin:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,via:!0};this._privateHeaders={"set-cookie":!1,"set-cookie2":!1};this._userAgent=`Mozilla/5.0 (${Ai.type()} ${Ai.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Ae.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new Ii(this);this._method=null;this._url=null;this._sync=!1;this._headers=null;this._loweredHeaders=null;this._mimeOverride=null;this._request=null;this._response=null;this._responseParts=null;this._responseHeaders=null;this._aborting=null;this._error=null;this._loadedBytes=0;this._totalBytes=0;this._lengthComputable=!1;this._anonymous=t==null?void 0:t.anon}static nodejsSet(t){Ae.prototype.nodejsSet(t)}nodejsSet(t){if("httpAgent"in t&&(this.nodejsHttpAgent=t.httpAgent),"httpsAgent"in t&&(this.nodejsHttpsAgent=t.httpsAgent),"baseUrl"in t){let r=t.baseUrl;if(r!==null&&!Ks.parse(r,!1,!0).protocol)throw new Ri("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new Ci(`HTTP method ${t} is not allowed in XHR`);let i=this._parseUrl(r);n===void 0&&(n=!0),this._method=t,this._url=i,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(Ae.OPENED),this._request=null,this._response=null,this.status=0,this.statusText="",this._responseParts=[],this._responseHeaders=null,this._loadedBytes=0,this._totalBytes=0,this._lengthComputable=!1}setRequestHeader(t,r){if(this.readyState!==Ae.OPENED)throw new Tr("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||n.startsWith("sec-")||n.startsWith("proxy-")||(r=r.toString(),n in this._loweredHeaders?(t=this._loweredHeaders[n],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[n]=t,this._headers[t]=r))}send(t){if(this.readyState!==Ae.OPENED)throw new Tr("XHR readyState must be OPENED");if(this._request)throw new Tr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new xi(`XHR request to ${this._url.href} failed: unsupported protocol '${this._url.protocol}'. Please use supported protocols like HTTP, HTTPS, or file.`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let r=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
420
- `):""}overrideMimeType(t){if([Ae.LOADING,Ae.DONE].includes(this.readyState))throw new Tr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new zs("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new xi("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(t){if(this._sync)throw new Error("Synchronous XHR processing not implemented");t!=null&&(this._method==="GET"||this._method==="HEAD")?t=null:t||="",this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let r=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,i=(this._url.protocol==="http:"?Js:wc).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:r});typeof t=="object"&&t instanceof Si.default&&t.pipe(i),this._request=i,this.timeout&&i.setTimeout(this.timeout,()=>this._onHttpTimeout(i)),i.on("response",o=>this._onHttpResponse(i,o)),i.on("error",()=>this._onHttpRequestError(i)),this.upload._startUpload(i),this._request===i&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof Si.default&&Object.assign(this._headers,t.getHeaders()),this._headers.Connection="keep-alive",this._headers.Host=this._url.host,this._anonymous&&(this._headers.Referer="about:blank"),this._headers["User-Agent"]=this._userAgent,this.upload._finalizeHeaders(this._headers,this._loweredHeaders)}_onHttpResponse(t,r){if(this._request!==t)return;if([301,302,303,307,308].includes(r.statusCode)){this._url=this._parseUrl(r.headers.location),this._method="GET","content-type"in this._loweredHeaders&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),"Content-Type"in this._headers&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),this._sendHxxpRequest();return}this._response=r,this._response.on("data",i=>this._onHttpResponseData(r,i)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=Js.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Ae.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ae.LOADING&&this._setReadyState(Ae.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ae.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let r=this._request;return this._setError(),r.abort(),this._setReadyState(Ae.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ae.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ae.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new zs(t);r.lengthComputable=this._lengthComputable,r.loaded=this._loadedBytes,r.total=this._totalBytes,this.dispatchEvent(r)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let r,n,i,o=this.nodejsBaseUrl===null?t:Ks.resolve(this.nodejsBaseUrl,t),a=Ks.parse(o,!1,!0);return a.hash=null,a.auth&&(i!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?i||(i=a.auth):(i||(i=a.substring(0,r)),n||(n=a.substring(r+1)))),(i||n)&&(a.auth=`${i}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let i=r.toLowerCase();this._privateHeaders[i]||(this._mimeOverride!==null&&i==="content-type"&&(n=this._mimeOverride),this._responseHeaders[i]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let i=0;i<t.length;i++)n[i]=t[i];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}},Ne=Ae;Ne.SyntaxError=Ri,Ne.ProgressEvent=zs,Ne.SecurityError=Ci,Ne.XMLHttpRequest=Ae,Ne.InvalidStateError=Tr,Ne.XMLHttpRequestUpload=Ii,Ne.UNSENT=0,Ne.OPENED=1,Ne.HEADERS_RECEIVED=2,Ne.LOADING=3,Ne.DONE=4;Object.assign(global,{xhr2:Ne,XMLHttpRequest:Ne});var vw=R(require("semver"));Ve();id();Jt();Tn();var Nd=R(require("chalk")),Sw=require("node:events");ae();Fn();Q();ae();bo();W();var bT=R(require("os")),od=R(require("path")),ad=R(require("chalk")),ic=require("fs");le();function TT(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=bT.homedir();(0,ic.mkdirSync)(od.resolve(n,".testim_logs"),{recursive:!0});let i=od.resolve(n,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${i}`),Xd&&console.log(`Call stack: ${s==null?void 0:s.stack}`),(t=s==null?void 0:s.message)!=null&&t.includes("Unable to compile TypeScript")&&((r=s.stack)!=null&&r.includes("runner/src"))&&process.argv.some(o=>o.includes("player-require-path"))&&(console.log(ad.default.red("Looks like you got a TypeScript compile error champ - but it's not a very good one because we use TypeScript in transpile-only mode")),console.log(ad.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,ic.writeFileSync)(i,`${s}
418
+ Browser session ended`),process.exit(0)};if(await Te(r)){let f=JSON.parse(Le.readFileSync(r));if(fw(f.pid)){let h=()=>fw(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await co();await Te(Hs)||await Le.promises.mkdir(Hs,{recursive:!0});let c=[...Tw(Hs,e,t,o).desiredCapabilities.chromeOptions.args,...yc.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],l={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=s.extensionPath?"http://localhost:3000/app/":new URL("?startMode=true",it||wr).href,m=await yc.launch({chromeFlags:c,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Hs,chromePath:o,envVars:l}),u={port:m.port,pid:m.pid,cdpUrl:await Rr(`localhost:${m.port}`)};return Le.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",i),m.process.once("close",i),{webdriverApi:u}}async function ux(s){let e=`${tr}/testim-full-master.zip`,t=yr.basename(e),r=yr.join(vt,t),n=yr.join(vt,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await Te(r)){let f=await Le.promises.stat(r);i=Date.now()-ox>f.mtimeMs}if(await Le.promises.mkdir(vt,{recursive:!0}),i){let f=(0,hw.default)("Downloading Testim Editor").start();await Ye(e,r);try{await Qe(r,n)}catch{await Le.promises.rm(r,{recursive:!0,force:!0}),await Ye(e,r);try{await Qe(r,n)}catch{throw await Le.promises.rm(r,{recursive:!0,force:!0}),f.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await Le.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Le.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await lx(s,o,n);await hn({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=Tw(Hs,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=(Kn(),Ke(Ih)),{SeleniumPerfStats:l}=(vs(),Ke(Ng)),d=new c;d.seleniumPerfStats=new l;let m=await d.initClient(a);bw=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":it||wr}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await Rr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function Tw(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];t&&i.push(`--load-extension=${t}`);try{let o=Wo();o.length&&o.forEach(a=>i.push(`--disable-features=${a}`))}catch{}return{logLevel:ix,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function px(){if(await Te(hc))try{let{webSocketDebuggerUrl:s}=await dx();await mx(s),await Le.promises.unlink(hc)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Le.promises.unlink(hc)}}async function dx(){let s=await Le.promises.readFile(hc,{encoding:"utf8"}),[e,t]=s.split(`
419
+ `).map(i=>i.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await Rr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function mx(s,e=100){let t=await fx(s,e);return nr(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function fx(s,e=100){let t=Ja({timeout:e}),r=new yw.default(s,t),n=nr(o=>{r.once("open",o)}).then(()=>{r.removeAllListeners()}),i=nr(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return Promise.race([n,i]).then(()=>r)}var gw,hw,yw,Le,yr,yc,ix,ox,Hs,ax,hc,bw,_d=I(()=>{"use strict";gw=R(require("ms")),hw=R(require("ora")),yw=R(require("ws")),Le=R(require("node:fs")),yr=R(require("node:path")),yc=R(require("chrome-launcher"));ue();bn();Q();Il();F();Go();Xa();ix=Oi?"verbose":"silent",ox=(0,gw.default)("1h"),Hs=yr.join(vt,"profile"),ax="DevToolsActivePort",hc=yr.join(Hs,ax);bw=!1});var LM=require("source-map-support/register");var Ai=R(require("os")),zs=R(require("url")),Ks=R(require("http")),wc=R(require("https")),Si=R(require("form-data")),Ei=class{constructor(){this.onloadstart=null;this.onprogress=null;this.onabort=null;this.onerror=null;this.onload=null;this.ontimeout=null;this.onloadend=null;this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]||=[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let i of r)i==null||i.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},Ii=class extends Ei{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(t!=null)if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let i=0;i<t.byteLength;i++)r[i]=n[i];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=t.byteOffset,i=new Uint8Array(t.buffer);for(let o=0;o<t.byteLength;o++)r[o]=i[o+n];this._body=r}else if(typeof t=="object"&&t instanceof Si.default)this._body=null;else throw new Error(`Unsupported send() data ${t}`)}_finalizeHeaders(t,r){this._contentType&&!("content-type"in r)&&(t["Content-Type"]=this._contentType),this._body&&(t["Content-Length"]=this._body.length.toString())}_startUpload(t){this._body&&t.write(this._body),t.end()}},qs=class{constructor(e){this.type=e;this.target=null;this.currentTarget=null;this.lengthComputable=!1;this.loaded=0;this.total=0;this.bubbles=!1;this.cancelable=!1}},Ri=class extends Error{},xi=class extends Error{},Ci=class extends Error{},br=class extends Error{},Ae=class extends Ei{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Ks.globalAgent;this.nodejsHttpsAgent=wc.globalAgent;this.nodejsBaseUrl=null;this._restrictedMethods={CONNECT:!0,TRACE:!0,TRACK:!0};this._restrictedHeaders={"accept-charset":!0,"accept-encoding":!0,"access-control-request-headers":!0,"access-control-request-method":!0,connection:!0,"content-length":!0,cookie:!0,cookie2:!0,date:!0,dnt:!0,expect:!0,host:!0,"keep-alive":!0,origin:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,via:!0};this._privateHeaders={"set-cookie":!1,"set-cookie2":!1};this._userAgent=`Mozilla/5.0 (${Ai.type()} ${Ai.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Ae.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new Ii(this);this._method=null;this._url=null;this._sync=!1;this._headers=null;this._loweredHeaders=null;this._mimeOverride=null;this._request=null;this._response=null;this._responseParts=null;this._responseHeaders=null;this._aborting=null;this._error=null;this._loadedBytes=0;this._totalBytes=0;this._lengthComputable=!1;this._anonymous=t==null?void 0:t.anon}static nodejsSet(t){Ae.prototype.nodejsSet(t)}nodejsSet(t){if("httpAgent"in t&&(this.nodejsHttpAgent=t.httpAgent),"httpsAgent"in t&&(this.nodejsHttpsAgent=t.httpsAgent),"baseUrl"in t){let r=t.baseUrl;if(r!==null&&!zs.parse(r,!1,!0).protocol)throw new Ri("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new Ci(`HTTP method ${t} is not allowed in XHR`);let i=this._parseUrl(r);n===void 0&&(n=!0),this._method=t,this._url=i,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(Ae.OPENED),this._request=null,this._response=null,this.status=0,this.statusText="",this._responseParts=[],this._responseHeaders=null,this._loadedBytes=0,this._totalBytes=0,this._lengthComputable=!1}setRequestHeader(t,r){if(this.readyState!==Ae.OPENED)throw new br("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||n.startsWith("sec-")||n.startsWith("proxy-")||(r=r.toString(),n in this._loweredHeaders?(t=this._loweredHeaders[n],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[n]=t,this._headers[t]=r))}send(t){if(this.readyState!==Ae.OPENED)throw new br("XHR readyState must be OPENED");if(this._request)throw new br("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new xi(`XHR request to ${this._url.href} failed: unsupported protocol '${this._url.protocol}'. Please use supported protocols like HTTP, HTTPS, or file.`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let r=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
420
+ `):""}overrideMimeType(t){if([Ae.LOADING,Ae.DONE].includes(this.readyState))throw new br("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new qs("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new xi("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(t){if(this._sync)throw new Error("Synchronous XHR processing not implemented");t!=null&&(this._method==="GET"||this._method==="HEAD")?t=null:t||="",this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let r=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,i=(this._url.protocol==="http:"?Ks:wc).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:r});typeof t=="object"&&t instanceof Si.default&&t.pipe(i),this._request=i,this.timeout&&i.setTimeout(this.timeout,()=>this._onHttpTimeout(i)),i.on("response",o=>this._onHttpResponse(i,o)),i.on("error",()=>this._onHttpRequestError(i)),this.upload._startUpload(i),this._request===i&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof Si.default&&Object.assign(this._headers,t.getHeaders()),this._headers.Connection="keep-alive",this._headers.Host=this._url.host,this._anonymous&&(this._headers.Referer="about:blank"),this._headers["User-Agent"]=this._userAgent,this.upload._finalizeHeaders(this._headers,this._loweredHeaders)}_onHttpResponse(t,r){if(this._request!==t)return;if([301,302,303,307,308].includes(r.statusCode)){this._url=this._parseUrl(r.headers.location),this._method="GET","content-type"in this._loweredHeaders&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),"Content-Type"in this._headers&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),this._sendHxxpRequest();return}this._response=r,this._response.on("data",i=>this._onHttpResponseData(r,i)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=Ks.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Ae.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ae.LOADING&&this._setReadyState(Ae.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ae.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let r=this._request;return this._setError(),r.abort(),this._setReadyState(Ae.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ae.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ae.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new qs(t);r.lengthComputable=this._lengthComputable,r.loaded=this._loadedBytes,r.total=this._totalBytes,this.dispatchEvent(r)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let r,n,i,o=this.nodejsBaseUrl===null?t:zs.resolve(this.nodejsBaseUrl,t),a=zs.parse(o,!1,!0);return a.hash=null,a.auth&&(i!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?i||(i=a.auth):(i||(i=a.substring(0,r)),n||(n=a.substring(r+1)))),(i||n)&&(a.auth=`${i}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let i=r.toLowerCase();this._privateHeaders[i]||(this._mimeOverride!==null&&i==="content-type"&&(n=this._mimeOverride),this._responseHeaders[i]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let i=0;i<t.length;i++)n[i]=t[i];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}},Ne=Ae;Ne.SyntaxError=Ri,Ne.ProgressEvent=qs,Ne.SecurityError=Ci,Ne.XMLHttpRequest=Ae,Ne.InvalidStateError=br,Ne.XMLHttpRequestUpload=Ii,Ne.UNSENT=0,Ne.OPENED=1,Ne.HEADERS_RECEIVED=2,Ne.LOADING=3,Ne.DONE=4;Object.assign(global,{xhr2:Ne,XMLHttpRequest:Ne});var vw=R(require("semver"));$e();id();Xt();bn();var Nd=R(require("chalk")),Sw=require("node:events");ae();Mn();Q();ae();bo();W();var bT=R(require("os")),od=R(require("path")),ad=R(require("chalk")),ic=require("fs");ue();function TT(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=bT.homedir();(0,ic.mkdirSync)(od.resolve(n,".testim_logs"),{recursive:!0});let i=od.resolve(n,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${i}`),Xd&&console.log(`Call stack: ${s==null?void 0:s.stack}`),(t=s==null?void 0:s.message)!=null&&t.includes("Unable to compile TypeScript")&&((r=s.stack)!=null&&r.includes("runner/src"))&&process.argv.some(o=>o.includes("player-require-path"))&&(console.log(ad.default.red("Looks like you got a TypeScript compile error champ - but it's not a very good one because we use TypeScript in transpile-only mode")),console.log(ad.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,ic.writeFileSync)(i,`${s}
421
421
  ${s==null?void 0:s.stack}
422
422
 
423
- ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}gn();var iR=A("process-handler"),wT=!1;function oR(s){return s instanceof Error?1:wT?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(he.SKIPPED)||[t,i].includes(he.FAILED)&&n===et.EVALUATING?!1:r!==!0)?1:0)}function aR(){try{ar("chromedriver").stop()}catch{}}function vT(){wT=!0}async function cd(s){s!=null&&s.stack&&(hs?console.error(s,s.stack):TT(s)),aR(),await iR.waitForFlush(),process.exit(oR(s))}ye();W();me();var gx=A("cli-entry");function hx(s){if(!vw.satisfies(process.version,s))throw new x(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=20,t=22,r=Number(process.versions.node.split(".")[0]),n=new Date("2026-04-30T00:00:00.000Z"),i=n<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new x(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&i)throw new x(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(Nd.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function yx(){console.log("Starting Testim.io CLI");let s=await Promise.resolve().then(()=>(F(),X));M("Starting Testim.io CLI"),bg(cd);try{hx(s.getEnginesVersion())}catch(e){console.log("Argument Error:",e.message),process.exit(1)}try{let e=await Promise.resolve().then(()=>(UT(),FT)),{program:t}=e;await O.fetch({proxy:t.proxy});let r=await e.process();if(M("in main, after options.process"),bm(global.proxyUri),Sw.EventEmitter.defaultMaxListeners="parallel"in r&&r.parallel>10?r.parallel*3:30,ym(r.project),nf("token"in r&&typeof r.token=="string"?r.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(r)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(Ss(),Sg));return await o()}if(s.isLoginMode(r))return;if(s.isCreatePrefetchedDataMode(r)){await ls(),await yi(r);let{preloadTests:o}=await Promise.resolve().then(()=>(Ko(),Uh));await o(r),!r.playerRequirePath&&r.mode!==J.EXTENSION&&await Cr(r.playerLocation,r.canary);let a=await rf();a.success?console.log(`created prefetched data at ${Zi()}`):console.error("failed to create prefetch data",a.error);return}let n=await Promise.resolve().then(()=>(ew(),ZT));if(s.isTunnelOnlyMode(r)){await n.init(r);let{serveTunneling:o}=await Promise.resolve().then(()=>(Pd(),Ad));await o(r);return}if(s.isAgentMode(r)){let{runAgentMode:o}=await Promise.resolve().then(()=>(_d(),ww));return o(r)}if(r.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(mu(),Bg)),{port:a}=await o(r);r.localRCASaver=`http://localhost:${a}`}r.exitCodeIgnoreFailingTests&&vT(),M("right before testRunner.init/prepareRunner.prepare"),await n.init(r);let i=await hT(r);return M("right after testRunner.init/prepareRunner.prepare"),await n.run(r,i)}catch(e){if(e instanceof Jr)return;let t=s.getArgsOnRemoteRunFailure();return t&&await ed({...t,error:e.message}).catch(()=>{}),e instanceof x?(console.log(Nd.default.red("Argument Error:",e.message)),e):(console.log("Error:",e.message),gx.error("runner ended with unexpected error",{err:e}),e)}}yx().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),cd(s)});
423
+ ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}fn();var iR=A("process-handler"),wT=!1;function oR(s){return s instanceof Error?1:wT?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(he.SKIPPED)||[t,i].includes(he.FAILED)&&n===Ze.EVALUATING?!1:r!==!0)?1:0)}function aR(){try{ar("chromedriver").stop()}catch{}}function vT(){wT=!0}async function cd(s){s!=null&&s.stack&&(fs?console.error(s,s.stack):TT(s)),aR(),await iR.waitForFlush(),process.exit(oR(s))}ye();W();me();var gx=A("cli-entry");function hx(s){if(!vw.satisfies(process.version,s))throw new x(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=20,t=22,r=Number(process.versions.node.split(".")[0]),n=new Date("2026-04-30T00:00:00.000Z"),i=n<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new x(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&i)throw new x(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(Nd.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function yx(){console.log("Starting Testim.io CLI");let s=await Promise.resolve().then(()=>(F(),X));M("Starting Testim.io CLI"),bg(cd);try{hx(s.getEnginesVersion())}catch(e){console.log("Argument Error:",e.message),process.exit(1)}try{let e=await Promise.resolve().then(()=>(UT(),FT)),{program:t}=e;await O.fetch({proxy:t.proxy});let r=await e.process();if(M("in main, after options.process"),bm(global.proxyUri),Sw.EventEmitter.defaultMaxListeners="parallel"in r&&r.parallel>10?r.parallel*3:30,ym(r.project),nf("token"in r&&typeof r.token=="string"?r.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(r)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(ws(),Sg));return await o()}if(s.isLoginMode(r))return;if(s.isCreatePrefetchedDataMode(r)){await as(),await yi(r);let{preloadTests:o}=await Promise.resolve().then(()=>(Ko(),Uh));await o(r),!r.playerRequirePath&&r.mode!==J.EXTENSION&&await xr(r.playerLocation,r.canary);let a=await rf();a.success?console.log(`created prefetched data at ${Zi()}`):console.error("failed to create prefetch data",a.error);return}let n=await Promise.resolve().then(()=>(ew(),ZT));if(s.isTunnelOnlyMode(r)){await n.init(r);let{serveTunneling:o}=await Promise.resolve().then(()=>(Pd(),Ad));await o(r);return}if(s.isAgentMode(r)){let{runAgentMode:o}=await Promise.resolve().then(()=>(_d(),ww));return o(r)}if(r.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(mu(),Bg)),{port:a}=await o(r);r.localRCASaver=`http://localhost:${a}`}r.exitCodeIgnoreFailingTests&&vT(),M("right before testRunner.init/prepareRunner.prepare"),await n.init(r);let i=await hT(r);return M("right after testRunner.init/prepareRunner.prepare"),await n.run(r,i)}catch(e){if(e instanceof zr)return;let t=s.getArgsOnRemoteRunFailure();return t&&await ed({...t,error:e.message}).catch(()=>{}),e instanceof x?(console.log(Nd.default.red("Argument Error:",e.message)),e):(console.log("Error:",e.message),gx.error("runner ended with unexpected error",{err:e}),e)}}yx().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),cd(s)});
424
424
  //# sourceMappingURL=cli.js.map