@testim/testim-cli 4.172.2 → 4.173.4

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,55 +1,55 @@
1
1
  #! /usr/bin/env node
2
- "use strict";var rw=Object.create;var gn=Object.defineProperty;var sw=Object.getOwnPropertyDescriptor;var iw=Object.getOwnPropertyNames;var nw=Object.getPrototypeOf,ow=Object.prototype.hasOwnProperty;var I=(s,e)=>()=>(s&&(e=s(s=0)),e);var z=(s,e)=>{for(var t in e)gn(s,t,{get:e[t],enumerable:!0})},Id=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of iw(e))!ow.call(s,i)&&i!==t&&gn(s,i,{get:()=>e[i],enumerable:!(r=sw(e,i))||r.enumerable});return s};var R=(s,e,t)=>(t=s!=null?rw(nw(s)):{},Id(e||!s||!s.__esModule?gn(t,"default",{value:s,enumerable:!0}):t,s)),ze=s=>Id(gn({},"__esModule",{value:!0}),s);var $e={};z($e,{log:()=>M,measure:()=>cw});function M(...s){if(!xd)return;let e=Date.now();console.log(`${e-aw} ${e-Rd} `,...s),Rd=e}function cw(s,e){if(!xd)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var xd,aw,Rd,We=I(()=>{"use strict";xd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,aw=Date.now(),Rd=Date.now()});var Kt,qr=I(()=>{"use strict";Kt="element-6066-11e4-a52e-4f735466cecf"});function se(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let i=Math.floor(Math.random()*e.length);t+=e[i]}return t}function Ke(s,e,t,r,i){let n="";return i=i?encodeURIComponent(i):"master",e&&t&&(n=`${s}/#/project/${e}/branch/${i}/test/${t}`,r&&(n+=`?result-id=${r}`)),n}function bc(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 Tc=I(()=>{"use strict"});var vc,Cd,Ad,En=I(()=>{vc={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"},Cd={"@applitools/eyes-sdk-core":"13.11.34-legacy.1","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"2.1.3","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.3",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.8.1",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6",express:"4.21.2",fkill:"7.2.1","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"1.1.4",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2","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"},Ad={node:">= 18.0.0"}});var yr,br,Pd,Vs,pw,Jt,kd,Od,In,st,_d,he,Dd,Ld,Rn,Ve,Sc,Nd,xn,Md,Fd,ex,tx,Ud,Bd,jd,$d,Ec,Wd,Ic,Vd,Gs,Gd,Rc,Hs,oe=I(()=>{"use strict";yr=process.env.SERVICES_HOST||"",br="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:yr,yr=process.env.SERVICES_HOST);Pd=process.env.TESTIM_REGION||"us-west-2",Vs=process.env.RUNNER_ENVIRONMENT||"production",pw={production:"",staging:".staging",development:".dev"},Jt=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${pw[Vs]||""}.testim.io`,kd=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Od=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),In=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),st=process.env.EDITOR_URL,_d=process.env.WEBSOCKET_HOST||`${yr}/ws`,he=()=>yr,Dd=parseInt(process.env.LOGGER_CONSOLE||"0",10),Ld=parseInt(process.env.LOGGER_DEBUG||"0",10),Rn=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),Ve=parseInt(process.env.IS_ON_PREM||"0",10),Sc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Nd=parseInt(process.env.DEBUG_MODE||"0",10),xn=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Md=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",Fd=process.env.CORALOGIX_PRIVATE_KEY||"",ex=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),tx=process.env.APPIUM_VERSION||"1.10.1",Ud=process.env.GATEWAY_URL,Bd=()=>process.env.EXTENSION_SERVICES_HOST||yr,jd=5*60*1e3,$d=40,Ec=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",Wd=process.env.TDC_DEVICES_API_PATH||"v0",Ic=process.env.TDC_APPS_API_PATH||"v1",Vd=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Gs=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Gd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,Rc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung",Hs=s=>{yr=s,process.env.SERVICES_HOST=s,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:yr}});var Hd,Cn,qd=I(()=>{"use strict";Hd=R(require("superagent"));oe();Cn=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=Fd,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=Hd.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 Kd={};z(Kd,{CoralogixTransport:()=>xc});var zd,dw,mw,xc,Jd=I(()=>{"use strict";zd=R(require("winston-transport"));qd();dw={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},mw=["err","error","reason","e"],xc=class extends zd.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new Cn({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:i,level:n,message:o,meta:a={},...c}=t,l={...a,...c},d={severity:dw[n],text:o,category:i||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 mw)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 hw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!Ve){let{CoralogixTransport:r}=(Jd(),ze(Kd)),i=new r({category:"ROOT"});s.push(i),e=()=>i.waitForFlush(),t=n=>i.setProxy(n)}if(Dd){let r={depth:5,colors:!0};s.push(new gt.transports.Console({format:gt.format.combine(gt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),gt.format.timestamp({format:"HH:mm:ss:SSS"}),gt.format.printf(i=>`[${i.timestamp}] ${i.level} ${i.category}: ${i.message} ${Pn.inspect(i.meta,r)}`))}))}return[s,e,t]}function rm(s){Cc=s}function sm(s){tm=s}function im(s){Ve||!s||Tw(s)}function Xd(s){return{projectId:tm,time:new Date().toISOString(),region:Ut.getRegion(),...Cc&&!s&&{executionId:Cc}}}function P(s){return new Ut(Sw.child({category:s}))}var Qd,gt,Pn,An,Zd,fw,gw,Yd,em,yw,bw,Tw,ww,vw,Sw,Cc,tm,Ut,W=I(()=>{"use strict";Qd=R(require("node:os")),gt=R(require("winston"));oe();Pn=R(require("node:util")),An=R(require("chalk")),Zd=R(require("dayjs"));F();fw=Qd.hostname(),gw=it();Yd={depth:5,colors:!0},em=(s,e,t)=>{let r=`[${(0,Zd.default)().format("HH:mm:ss:SSS")}]`,i=Pn.inspect(e,Yd),n=Pn.inspect(t,Yd);return`${An.default.white(r)} ${An.default.reset()}SessionPlayer-${An.default.red(s)} ${i} ${n}`},[yw,bw,Tw]=hw(),ww=Ld?"debug":"info",vw={release:Boolean(!1),branch:"test"},Sw=gt.createLogger({levels:gt.config.syslog.levels,level:ww,transports:yw,defaultMeta:{name:"runner",hostname:fw,nodeVersion:process.version,runnerVersion:gw,...vw}}),Cc=null,tm=null;Ut=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){Ut.region=e}static getRegion(){return Ut.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:i}=r;try{this._logger.log(e,{meta:r,message:t,...Xd(i)})}catch(n){try{this._logger.log("crit",{message:`failed to log message ${n.message}, ${n.stack}`,...Xd(i)})}catch{}}}waitForFlush(){return bw()}}});var Dn,zr,x,Yt,Tr,At,kn,Kr,ce,qs,nt,Xt,Pt,On,Jr,_n,zs,X=I(()=>{"use strict";Dn=require("p-retry"),zr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},x=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Yt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},Tr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},At=class extends Dn.AbortError{},kn=class extends Dn.AbortError{},Kr=class extends Dn.AbortError{},ce=class extends Error{},qs=class extends Error{},nt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Xt=class extends nt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Pt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},On=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}},_n=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 Ac(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function pe(s){return(0,am.setTimeout)(s)}function Pc(s,e){let t=new Promise((r,i)=>{e.onabort=()=>{i(e.reason)}});return Promise.race([s,t])}function le(s,e,t="Timeout Error"){In&&!nm&&(nm=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ce(t);return e=In?Number(In)||6e5:e,Promise.race([s,pe(e).then(()=>{throw r})])}async function ie(s,e,{concurrency:t}={}){if(t){om||=(await import("p-limit")).default;let r=om(t);return await Promise.all(Array.from(s,(i,n)=>r(()=>e(i,n))))}return await Promise.all(Array.from(s,e))}function Qt(s){return new Promise((e,t)=>{s((r,i)=>r?t(r):e(i))})}var am,nm,om,kc=I(()=>{"use strict";am=require("timers/promises");X();oe();nm=!1});var Js,cm,Iw,Ks,lm,Rw,xw,um,pm=I(()=>{"use strict";Js=R(require("lodash"));oe();cm=require("dns");W();kc();Iw=P("http-request-counters"),Ks=!1,lm=async()=>{if(Ve)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ie(s,t=>cm.promises.lookup(t)));return e||(Ks=!0),e}catch{return Iw.error("network connectivity test failed"),Ks=!0,!1}},Rw=Js.throttle(lm,10*1e3),xw=60*1e3*15,um=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(i,n){let o=i.get(n)||0;i.set(n,o+1),setTimeout(()=>{let a=i.get(n)||1;i.set(n,a-1)},xw)}function t(i,n=i.name){return async function(...o){e(s.call,n);try{let a=await i.call(null,...o);return e(s.success,n),a}catch(a){throw e(s.fail,n),Ks||Rw(),a}}}async function r(){if(Ks||!await lm())return!1;let i=Js.sum([...s.fail.values()]),n=Js.sum([...s.call.values()]);return i<n*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Ks,t}});var Je={};z(Je,{deleteReq:()=>Ys,didNetworkConnectivityTestFail:()=>Fc,download:()=>Nc,get:()=>we,getFullRes:()=>Ow,getText:()=>Qs,head:()=>_w,isNetworkHealthy:()=>Mc,post:()=>Ge,postForm:()=>Xs,postText:()=>Dc,put:()=>Lc});function Aw(){return global.caFileContent}function Pw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function kw(){return!ht.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(ht.default),global.proxyUri}function wr(s,e=!1){let t=Aw();t&&s.ca(t);let r=!e&&kw();r&&s.proxy(r)}async function dm(s,e,t={},r=Yr,i=0){let n=ht.default.post(s).send(e).timeout(r).set(t);wr(n),i&&n.retry(i);try{return await n}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function _c(s,e,t={},r=Yr,{isBinary:i=!1,skipProxy:n=!1}={}){let o=ht.default.get(s).query(e||{}).timeout(r).set(t);return i&&o.buffer(!0),wr(o,n),await o}var ht,Oc,ot,Yr,Cw,Bt,Ys,Ge,Xs,Qs,Dc,we,Ow,_w,Lc,Nc,Mc,Fc,He=I(()=>{"use strict";ht=R(require("superagent"));W();pm();Oc=P("http-request"),ot=um(),Yr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,Cw=6e4;Bt=(s,e,t)=>{let r=e.response;e.response instanceof ht.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 i=new Error("").stack;throw Oc.error(s,{...t,error:e,logErrorAndRethrowStack:i}),e};Ys=ot(async(s,e={},t={},r=Yr)=>{try{let i=ht.default.delete(s).send(e).timeout(r).set(t);wr(i);let n=await i;return n.type==="text/plain"?n.text:n.body}catch(i){return Bt("failed to delete request",i,{url:s})}}),Ge=ot(async({url:s,body:e,headers:t,timeout:r,retry:i})=>{try{let n=await dm(s,e,t,r,i);return n.type==="text/plain"?n.text:n.body}catch(n){return Bt("failed to post request",n,{url:s})}});Xs=ot(async(s,e,t,r={},i=Yr)=>{let n=ht.default.post(s).type("form").timeout(i).set(r);n.field(e),Object.entries(t).forEach(([o,a])=>{n.attach(o,a.buffer,a.fileName)}),wr(n);try{let o=await n;return o.type==="text/plain"?o.text:o.body}catch(o){return Bt("failed to post request",o,{url:s})}});Qs=ot(async(s,e,t)=>{try{return(await _c(s,e,t)).text}catch(r){return Bt("failed to getText request",r,{url:s,query:e})}}),Dc=ot(async({url:s,body:e,headers:t,timeout:r,retry:i})=>{try{return(await dm(s,e,t,r,i)).text}catch(n){return Bt("failed to post request",n,{url:s})}}),we=ot(async(s,e,t,r,i)=>{try{return(await _c(s,e,t,r,i)).body}catch(n){return Bt("failed to get request",n,{url:s,query:e})}}),Ow=ot((s,e,t,r)=>_c(s,e,t,r)),_w=ot(async s=>{let e=ht.default.head(s).timeout(Yr);wr(e);try{return await e}catch(t){return Bt("failed to head request",t,{url:s})}}),Lc=ot(async(s,e,t={},r=Yr)=>{let i=ht.default.put(s).send(e).timeout(r).set(t);wr(i);try{return(await i).body}catch(n){return Bt("failed to put request",n,{url:s})}}),Nc=ot(async s=>{Oc.info("start to download",{url:s});let e=ht.default.get(s).set("User-Agent","Testim.io").timeout(Cw).buffer(!0).parse(Pw);wr(e);try{let t=await e;return Oc.info("finished to download",{url:s}),t}catch(t){return Bt("failed to download",t,{url:s})}}),Mc=ot.isNetworkHealthy,Fc=ot.didNetworkConnectivityTestFail});function yt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=jt.resolve(__dirname,"../../"):s=jt.resolve(__dirname,""),s):process.cwd()}function Ln(s,e){return Me(s)?e||jt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||jt.basename(s)}function it(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function jc(){try{return Ad.node}catch{return""}}async function gm(s,e,t=!0){let r=await at.promises.readdir(s,{withFileTypes:!0});await at.promises.mkdir(e,{recursive:t});for(let i of r){let n=jt.join(s,i.name),o=jt.join(e,i.name);i.isDirectory()?await gm(n,o):await at.promises.copyFile(n,o)}}async function ye(s){try{return await at.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var jt,mm,fm,at,Dw,$t,Ye,Nn,Uc,ct,Bc,hm=I(()=>{"use strict";jt=R(require("node:path"));Tc();En();mm=R(require("unzip-stream")),fm=R(require("p-retry")),at=require("node:fs"),Dw=3;$t=async s=>{let e=await Promise.resolve().then(()=>(He(),Je));return(0,fm.default)(()=>e.download(s),{retries:Dw,factor:1})},Ye=async(s,e)=>{let t=await $t(s);return at.promises.writeFile(e,t.body)};Nn=async(s,e)=>{let t=Ln(s,e);return Me(s)?Ye(s,t):at.promises.copyFile(s,t)},Uc=async s=>Me(s)?$t(s):at.promises.readFile(s),ct=async(s,e)=>(0,at.createReadStream)(s).pipe(mm.Extract({path:e})),Bc=s=>(0,at.statSync)(s).size/1e6});var Wt={};z(Wt,{APPIUM_SESSION_MESSAGE:()=>Hc,CLI_MODE:()=>K,MOBILE_APP_SOURCE:()=>Mn,MOBILE_RUN_SKIP_REASON:()=>Gc,OPERANDS:()=>ei,REGION_CONFIG:()=>Qr,X_HEADER_RUNNER_ID:()=>qc,gridMessages:()=>bt,gridTypes:()=>D,mobileWeb:()=>Wc,runnerStatus:()=>$c,runnerTestStatus:()=>fe,socketEventTypes:()=>kt,stepResult:()=>Xr,test:()=>Vc,testRunStatus:()=>Zs,testStatus:()=>Xe,timeoutMessages:()=>Pe});var Pe,Zs,$c,fe,Xe,bt,Wc,Vc,kt,K,D,Xr,Mn,Gc,Hc,qc,Qr,ei,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"},Zs={COMPLETED:"completed"},$c={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},fe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Xe={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},bt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Wc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Vc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},kt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},K={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},D={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",P_CLOUDY:"pcloudy"},Xr={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"},Mn={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Gc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Hc={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"},qc="X-Testim-Runner-ID",Qr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"},ei=(t=>(t.AND="AND",t.OR="OR",t))(ei||{})});function ti(s,e){var t,r,i,n,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(i=s.browser)==null?void 0:i.toLowerCase()]:(n=s.testConfigNames)!=null&&n.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 Lw(){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 ri,ym,Qe,Nw,Mw,Fw,Uw,Bw,zc,Kc,bm=I(()=>{"use strict";ae();ri=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},ym=s=>Boolean(s.resultId&&s.source==="remote-run"),Qe=(s,e)=>s.testStatus===Xe.QUARANTINE&&!ym(e)&&!e.runQuarantinedTests;Nw=s=>Boolean(s.loginMode),Mw=s=>Boolean(s.tunnelOnlyMode),Fw=s=>Boolean(s.createPrefechedData),Uw=s=>Boolean(s.installLazyDepsMode),Bw=s=>Boolean(s.agentMode),zc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Kc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Un(s=0){return Fn.default.duration(s).format("HH:mm:ss.SSS")}function Jc(s=0){return Fn.default.duration(s).asSeconds()}var Fn,Tm,Bn,wm=I(()=>{"use strict";Fn=R(require("dayjs")),Tm=R(require("dayjs/plugin/duration"));Fn.default.extend(Tm.default);Bn=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 si,Zr,Zt,vm,es,Sm=I(()=>{"use strict";ae();si=s=>!(!s||"fileName"in s),Zr=(s,e)=>{if(e===D.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Zt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},vm=s=>s===D.TESTIM_TVC,es=(s,e)=>vm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Yc(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 Em=I(()=>{"use strict"});var Q={};z(Q,{OSS:()=>ts,TESTIM_BROWSER_DIR:()=>Vt,buildBasicHeader:()=>bc,calcPercentile:()=>Wn,copyDir:()=>gm,delay:()=>pe,doesPathExist:()=>ye,download:()=>$t,downloadAndSave:()=>Ye,extractElementId:()=>Fe,formatTimeoutDuration:()=>Bn,getArgsOnRemoteRunFailure:()=>Lw,getBrowserInfo:()=>$w,getCdpAddressForHost:()=>Er,getCliLocation:()=>yt,getDuration:()=>Un,getDurationSec:()=>Jc,getEnginesVersion:()=>jc,getEnvironmentGitBranch:()=>Sr,getLinksFromUnescapeHTML:()=>oi,getLocalFileSizeInMB:()=>Bc,getMemorySnapshot:()=>Yc,getPlanType:()=>$n,getRunConfigByBrowserName:()=>ii,getRunnerVersion:()=>it,getSource:()=>Nn,getSourceAsBuffer:()=>Uc,getSourcePath:()=>Ln,getTestUrl:()=>Ke,getUniqBrowsers:()=>ti,groupTestsByRetries:()=>Qc,guid:()=>se,hasTestPlanFlag:()=>ri,isAgentMode:()=>Bw,isAppFromDevice:()=>si,isAppFromDeviceDisabled:()=>es,isCreatePrefetchedDataMode:()=>Fw,isInstallLazyDepsMode:()=>Uw,isLoginMode:()=>Nw,isMobileProject:()=>Zt,isPromise:()=>Ac,isQuarantineAndNotRemoteRun:()=>Qe,isRemoteRun:()=>ym,isTestimVirtualGrid:()=>vm,isTunnelOnlyMode:()=>Mw,isURL:()=>Me,promiseAbort:()=>Pc,promiseFromCallback:()=>Qt,promiseMap:()=>ie,promiseTimeout:()=>le,removePropertyFromObject:()=>jn,replaceArgsWithNoDashes:()=>zc,sanitizeNumberValue:()=>vr,shouldBlockVirtualIosBuild:()=>Zr,spreadObjectToArgs:()=>Kc,unescapeHTML:()=>ni,unzipFile:()=>ct});function vr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function $w(s){return s=s.toLowerCase(),Xc.find(e=>e.browserValue===s)}function ii(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Xc.find(n=>n.browserName.toLowerCase()===s||s.includes(n.synonyms))||Xc[0],i=ts.find(n=>n.osName==="Windows 10");return e&&(e.platform?i=ts.find(n=>n.sl.platform===e.platform):e.platformName&&(i=ts.find(n=>n.sl.platformName===e.platformName))),t&&(t.os_version?i=ts.find(n=>n.bs.os_version===t.os_version):t.platform&&(i=ts.find(n=>n.bs.platform===t.platform))),rs.merge(r,i)}function Sr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function jn(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&jn(s[r],e,t))}function Fe(s){return s.ELEMENT||s[Kt]}function $n(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Qc(s=[]){return rs.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((n,o)=>{let a=typeof n.retryCount=="number"?n.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?n.startTime-o.startTime:(n.retryCount??0)-(o.retryCount??0)}),i=rs.cloneDeep(r.at(-1));return i&&(i.retryTestResults=r,e.push(i)),e},[]).compact().value()}function ni(s){return Am.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function oi(s){return[...Am.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function Er(s,e){let t=await Promise.resolve().then(()=>(He(),Je));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var Rm,rs,xm,Cm,jw,Vt,Im,ts,Xc,Wn,Am,F=I(()=>{"use strict";Rm=R(require("os")),rs=R(require("lodash")),xm=R(require("path")),Cm=require("linkedom");qr();hm();bm();wm();Tc();kc();Sm();Em();jw=Rm.homedir(),Vt=xm.join(jw,".testim-browser-profile"),Im="133",ts=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Xc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:Im},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:Im},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"}];Wn=(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,i)=>r-i),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};Am=new Cm.DOMParser});var Zc={};z(Zc,{$schema:()=>Ww,default:()=>zw,definitions:()=>Vw,properties:()=>qw,required:()=>Hw,type:()=>Gw});var Ww,Vw,Gw,Hw,qw,zw,Pm=I(()=>{Ww="http://json-schema.org/draft-07/schema#",Vw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},Gw="object",Hw=["entries"],qw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},zw={$schema:Ww,definitions:Vw,type:Gw,required:Hw,properties:qw}});async function Mm(){try{return await le(Vn.promises.readFile(zn()).then(async s=>{let e=await Nm;return Yw(e,s)}),3e4)}catch{return{}}}function Yw(s,e){let t=e.slice(0,16),r=e.slice(16),i=Buffer.from(s),n=is.createDecipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),t),o=n.update(r);return JSON.parse(Buffer.concat([o,n.final()]))}function Ot(s,e,t=Kw,r=void 0){return async()=>{if(!_m)return await s();let i=e;r&&(e+=JSON.stringify(r));let n=await tl(e);if(n)return ai.debug("cache hit:",{fnName:e}),n;if(ai.debug("cache miss:",{fnName:e}),!Dm)throw new Error(`Attempted to rebuild cache for ${i}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Xw(e,o,t),o}}async function tl(s){let t=(await Kn)[s];if(!t)return;let{value:r,expiry:i}=t;if(!(i<Date.now())&&r)return r}async function Xw(s,e,t){if(el)throw ai.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 Kn;r[s]={value:e,expiry:Date.now()+t},Lm=new Promise(i=>{qn=i}),Jw(r)}catch{ai.error("failed updating cache")}}async function ns(){let s=await Kn;Object.keys(s).forEach(e=>{delete s[e]})}function Fm(s){_m=s}function Qw(s=!0){Dm=s}async function Um(){try{return el=!0,await Lm}finally{el=!1}}function Bm(s){Hn=s,Kn=Mm()}var Vn,Gn,is,km,ai,Hn,Om,qn,_m,Dm,el,Lm,Nm,Kw,zn,Kn,Jw,jm,$m,Ox,Wm,er=I(()=>{"use strict";Vn=R(require("fs")),Gn=R(require("path")),is=R(require("crypto"));F();km=require("lodash");W();ai=P("local cache"),Hn=Gn.resolve(yt(),"testim-cache"),_m=!0,Dm=!0,el=!1,Lm=new Promise(s=>{qn=s}),Nm=new Promise(s=>{Om=s}),Kw=1e3*60*60*3,zn=()=>Gn.resolve(Gn.resolve(Hn,"testim.cache"));Kn=Mm(),Jw=(0,km.debounce)(async s=>{let e;try{let t=await Nm,r=is.randomBytes(16),i=JSON.stringify(s),n=Buffer.from(t),o=is.createCipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(i),o.final()]);await ye(Hn)||await Vn.promises.mkdir(Hn,{recursive:!0}),await Vn.promises.writeFile(zn(),a)}catch(t){ai.error("failed saving cache",{err:t}),e=t}qn(e?{success:!1,error:e}:{success:!0})},200);jm=Om,$m=Fm.bind(void 0,!1),Ox=Fm.bind(void 0,!0),Wm=()=>Qw(!1)});function Jn(){return{cliLocation:yt(),userInfo:os.userInfo(),platform:os.platform(),release:os.release()}}var os,rl=I(()=>{"use strict";os=R(require("node:os"));F()});function Zw(s){try{return Yn.resolve(Yn.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 tr(s){let e=Zw(s);return require(e)}var Yn,ci=I(()=>{"use strict";Yn=R(require("path"))});function ev(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function tv(s){return/The "to" argument must be of type string./.exec(s)}function qm(s,e,t){let r=ev(s),i=tv(s);return r||i?(Hm.info("Failed to install package due to insufficient write access",{...Jn(),package:t,path:r}),console.error(`
2
+ "use strict";var ZT=Object.create;var fn=Object.defineProperty;var ew=Object.getOwnPropertyDescriptor;var tw=Object.getOwnPropertyNames;var rw=Object.getPrototypeOf,sw=Object.prototype.hasOwnProperty;var I=(s,e)=>()=>(s&&(e=s(s=0)),e);var z=(s,e)=>{for(var t in e)fn(s,t,{get:e[t],enumerable:!0})},Sd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of tw(e))!sw.call(s,i)&&i!==t&&fn(s,i,{get:()=>e[i],enumerable:!(r=ew(e,i))||r.enumerable});return s};var R=(s,e,t)=>(t=s!=null?ZT(rw(s)):{},Sd(e||!s||!s.__esModule?fn(t,"default",{value:s,enumerable:!0}):t,s)),ze=s=>Sd(fn({},"__esModule",{value:!0}),s);var $e={};z($e,{log:()=>M,measure:()=>nw});function M(...s){if(!Id)return;let e=Date.now();console.log(`${e-iw} ${e-Ed} `,...s),Ed=e}function nw(s,e){if(!Id)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var Id,iw,Ed,We=I(()=>{"use strict";Id=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,iw=Date.now(),Ed=Date.now()});var Kt,Vr=I(()=>{"use strict";Kt="element-6066-11e4-a52e-4f735466cecf"});function se(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let i=Math.floor(Math.random()*e.length);t+=e[i]}return t}function Ke(s,e,t,r,i){let n="";return i=i?encodeURIComponent(i):"master",e&&t&&(n=`${s}/#/project/${e}/branch/${i}/test/${t}`,r&&(n+=`?result-id=${r}`)),n}function gc(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 hc=I(()=>{"use strict"});var bc,Rd,xd,Sn=I(()=>{bc={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"},Rd={"@applitools/eyes-sdk-core":"13.11.34-legacy.1","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"2.1.3","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.3",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.8.1",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6",express:"4.21.2",fkill:"7.2.1","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"1.1.4",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2","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"},xd={node:">= 18.0.0"}});var hr,yr,Ad,Vs,cw,Jt,Cd,Pd,En,st,kd,he,Od,_d,In,Ve,Tc,Ld,Rn,Dd,Nd,XR,YR,Md,Fd,Ud,Bd,wc,jd,vc,$d,Gs,Hs,ae=I(()=>{"use strict";hr=process.env.SERVICES_HOST||"https://services.testim.io",yr="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:hr,hr=process.env.SERVICES_HOST);Ad=process.env.TESTIM_REGION||"us-west-2",Vs=process.env.RUNNER_ENVIRONMENT||"production",cw={production:"",staging:".staging",development:".dev"},Jt=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${cw[Vs]||""}.testim.io`,Cd=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Pd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),En=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),st=process.env.EDITOR_URL,kd=process.env.WEBSOCKET_HOST||`${hr}/ws`,he=()=>hr,Od=parseInt(process.env.LOGGER_CONSOLE||"0",10),_d=parseInt(process.env.LOGGER_DEBUG||"0",10),In=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),Ve=parseInt(process.env.IS_ON_PREM||"0",10),Tc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Ld=parseInt(process.env.DEBUG_MODE||"0",10),Rn=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Dd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",Nd=process.env.CORALOGIX_PRIVATE_KEY||"d0eb01da-f966-1663-63c6-8871225d7c39",XR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),YR=process.env.APPIUM_VERSION||"1.10.1",Md=process.env.GATEWAY_URL,Fd=()=>process.env.EXTENSION_SERVICES_HOST||hr,Ud=5*60*1e3,Bd=40,wc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",jd=process.env.TDC_DEVICES_API_PATH||"v0",vc=process.env.TDC_APPS_API_PATH||"v1",$d=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Gs=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Hs=s=>{hr=s,process.env.SERVICES_HOST=s,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:hr}});var Wd,xn,Vd=I(()=>{"use strict";Wd=R(require("superagent"));ae();xn=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=Nd,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=Wd.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 Hd={};z(Hd,{CoralogixTransport:()=>Sc});var Gd,lw,uw,Sc,qd=I(()=>{"use strict";Gd=R(require("winston-transport"));Vd();lw={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},uw=["err","error","reason","e"],Sc=class extends Gd.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new xn({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:i,level:n,message:o,meta:a={},...c}=t,l={...a,...c},d={severity:lw[n],text:o,category:i||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 uw)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 mw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!Ve){let{CoralogixTransport:r}=(qd(),ze(Hd)),i=new r({category:"ROOT"});s.push(i),e=()=>i.waitForFlush(),t=n=>i.setProxy(n)}if(Od){let r={depth:5,colors:!0};s.push(new gt.transports.Console({format:gt.format.combine(gt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),gt.format.timestamp({format:"HH:mm:ss:SSS"}),gt.format.printf(i=>`[${i.timestamp}] ${i.level} ${i.category}: ${i.message} ${Cn.inspect(i.meta,r)}`))}))}return[s,e,t]}function Zd(s){Ec=s}function em(s){Qd=s}function tm(s){Ve||!s||hw(s)}function Kd(s){return{projectId:Qd,time:new Date().toISOString(),region:Ut.getRegion(),...Ec&&!s&&{executionId:Ec}}}function P(s){return new Ut(Tw.child({category:s}))}var Jd,gt,Cn,An,Xd,pw,dw,zd,Yd,fw,gw,hw,yw,bw,Tw,Ec,Qd,Ut,W=I(()=>{"use strict";Jd=R(require("node:os")),gt=R(require("winston"));ae();Cn=R(require("node:util")),An=R(require("chalk")),Xd=R(require("dayjs"));F();pw=Jd.hostname(),dw=it();zd={depth:5,colors:!0},Yd=(s,e,t)=>{let r=`[${(0,Xd.default)().format("HH:mm:ss:SSS")}]`,i=Cn.inspect(e,zd),n=Cn.inspect(t,zd);return`${An.default.white(r)} ${An.default.reset()}SessionPlayer-${An.default.red(s)} ${i} ${n}`},[fw,gw,hw]=mw(),yw=_d?"debug":"info",bw={release:Boolean(!1),branch:"test"},Tw=gt.createLogger({levels:gt.config.syslog.levels,level:yw,transports:fw,defaultMeta:{name:"runner",hostname:pw,nodeVersion:process.version,runnerVersion:dw,...bw}}),Ec=null,Qd=null;Ut=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){Ut.region=e}static getRegion(){return Ut.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:i}=r;try{this._logger.log(e,{meta:r,message:t,...Kd(i)})}catch(n){try{this._logger.log("crit",{message:`failed to log message ${n.message}, ${n.stack}`,...Kd(i)})}catch{}}}waitForFlush(){return gw()}}});var _n,Gr,x,Xt,br,Ct,Pn,Hr,ce,qs,nt,Yt,Pt,kn,qr,On,zs,Y=I(()=>{"use strict";_n=require("p-retry"),Gr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},x=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Xt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},br=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},Ct=class extends _n.AbortError{},Pn=class extends _n.AbortError{},Hr=class extends _n.AbortError{},ce=class extends Error{},qs=class extends Error{},nt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Yt=class extends nt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Pt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},kn=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},qr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},On=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 Ic(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function pe(s){return(0,im.setTimeout)(s)}function Rc(s,e){let t=new Promise((r,i)=>{e.onabort=()=>{i(e.reason)}});return Promise.race([s,t])}function le(s,e,t="Timeout Error"){En&&!rm&&(rm=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ce(t);return e=En?Number(En)||6e5:e,Promise.race([s,pe(e).then(()=>{throw r})])}async function ie(s,e,{concurrency:t}={}){if(t){sm||=(await import("p-limit")).default;let r=sm(t);return await Promise.all(Array.from(s,(i,n)=>r(()=>e(i,n))))}return await Promise.all(Array.from(s,e))}function Qt(s){return new Promise((e,t)=>{s((r,i)=>r?t(r):e(i))})}var im,rm,sm,xc=I(()=>{"use strict";im=require("timers/promises");Y();ae();rm=!1});var Js,nm,vw,Ks,om,Sw,Ew,am,cm=I(()=>{"use strict";Js=R(require("lodash"));ae();nm=require("dns");W();xc();vw=P("http-request-counters"),Ks=!1,om=async()=>{if(Ve)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ie(s,t=>nm.promises.lookup(t)));return e||(Ks=!0),e}catch{return vw.error("network connectivity test failed"),Ks=!0,!1}},Sw=Js.throttle(om,10*1e3),Ew=60*1e3*15,am=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(i,n){let o=i.get(n)||0;i.set(n,o+1),setTimeout(()=>{let a=i.get(n)||1;i.set(n,a-1)},Ew)}function t(i,n=i.name){return async function(...o){e(s.call,n);try{let a=await i.call(null,...o);return e(s.success,n),a}catch(a){throw e(s.fail,n),Ks||Sw(),a}}}async function r(){if(Ks||!await om())return!1;let i=Js.sum([...s.fail.values()]),n=Js.sum([...s.call.values()]);return i<n*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Ks,t}});var Je={};z(Je,{deleteReq:()=>Xs,didNetworkConnectivityTestFail:()=>Lc,download:()=>Oc,get:()=>we,getFullRes:()=>Pw,getText:()=>Pc,head:()=>kw,isNetworkHealthy:()=>_c,post:()=>Ge,postForm:()=>Ys,postText:()=>Cw,put:()=>kc});function Rw(){return global.caFileContent}function xw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function Aw(){return!ht.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(ht.default),global.proxyUri}function Tr(s,e=!1){let t=Rw();t&&s.ca(t);let r=!e&&Aw();r&&s.proxy(r)}async function lm(s,e,t={},r=zr,i=0){let n=ht.default.post(s).send(e).timeout(r).set(t);Tr(n),i&&n.retry(i);try{return await n}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Cc(s,e,t={},r=zr,{isBinary:i=!1,skipProxy:n=!1}={}){let o=ht.default.get(s).query(e||{}).timeout(r).set(t);return i&&o.buffer(!0),Tr(o,n),await o}var ht,Ac,ot,zr,Iw,Bt,Xs,Ge,Ys,Pc,Cw,we,Pw,kw,kc,Oc,_c,Lc,He=I(()=>{"use strict";ht=R(require("superagent"));W();cm();Ac=P("http-request"),ot=am(),zr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,Iw=6e4;Bt=(s,e,t)=>{let r=e.response;e.response instanceof ht.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 i=new Error("").stack;throw Ac.error(s,{...t,error:e,logErrorAndRethrowStack:i}),e};Xs=ot(async(s,e={},t={},r=zr)=>{try{let i=ht.default.delete(s).send(e).timeout(r).set(t);Tr(i);let n=await i;return n.type==="text/plain"?n.text:n.body}catch(i){return Bt("failed to delete request",i,{url:s})}}),Ge=ot(async({url:s,body:e,headers:t,timeout:r,retry:i})=>{try{let n=await lm(s,e,t,r,i);return n.type==="text/plain"?n.text:n.body}catch(n){return Bt("failed to post request",n,{url:s})}});Ys=ot(async(s,e,t,r={},i=zr)=>{let n=ht.default.post(s).type("form").timeout(i).set(r);n.field(e),Object.entries(t).forEach(([o,a])=>{n.attach(o,a.buffer,a.fileName)}),Tr(n);try{let o=await n;return o.type==="text/plain"?o.text:o.body}catch(o){return Bt("failed to post request",o,{url:s})}});Pc=ot(async(s,e,t)=>{try{return(await Cc(s,e,t)).text}catch(r){return Bt("failed to getText request",r,{url:s,query:e})}}),Cw=ot(async({url:s,body:e,headers:t,timeout:r,retry:i})=>{try{return(await lm(s,e,t,r,i)).text}catch(n){return Bt("failed to post request",n,{url:s})}}),we=ot(async(s,e,t,r,i)=>{try{return(await Cc(s,e,t,r,i)).body}catch(n){return Bt("failed to get request",n,{url:s,query:e})}}),Pw=ot((s,e,t,r)=>Cc(s,e,t,r)),kw=ot(async s=>{let e=ht.default.head(s).timeout(zr);Tr(e);try{return await e}catch(t){return Bt("failed to head request",t,{url:s})}}),kc=ot(async(s,e,t={},r=zr)=>{let i=ht.default.put(s).send(e).timeout(r).set(t);Tr(i);try{return(await i).body}catch(n){return Bt("failed to put request",n,{url:s})}}),Oc=ot(async s=>{Ac.info("start to download",{url:s});let e=ht.default.get(s).set("User-Agent","Testim.io").timeout(Iw).buffer(!0).parse(xw);Tr(e);try{let t=await e;return Ac.info("finished to download",{url:s}),t}catch(t){return Bt("failed to download",t,{url:s})}}),_c=ot.isNetworkHealthy,Lc=ot.didNetworkConnectivityTestFail});function yt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=jt.resolve(__dirname,"../../"):s=jt.resolve(__dirname,""),s):process.cwd()}function Ln(s,e){return Me(s)?e||jt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||jt.basename(s)}function it(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Mc(){try{return xd.node}catch{return""}}async function dm(s,e,t=!0){let r=await at.promises.readdir(s,{withFileTypes:!0});await at.promises.mkdir(e,{recursive:t});for(let i of r){let n=jt.join(s,i.name),o=jt.join(e,i.name);i.isDirectory()?await dm(n,o):await at.promises.copyFile(n,o)}}async function ye(s){try{return await at.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var jt,um,pm,at,Ow,$t,Xe,Dn,Dc,ct,Nc,mm=I(()=>{"use strict";jt=R(require("node:path"));hc();Sn();um=R(require("unzip-stream")),pm=R(require("p-retry")),at=require("node:fs"),Ow=3;$t=async s=>{let e=await Promise.resolve().then(()=>(He(),Je));return(0,pm.default)(()=>e.download(s),{retries:Ow,factor:1})},Xe=async(s,e)=>{let t=await $t(s);return at.promises.writeFile(e,t.body)};Dn=async(s,e)=>{let t=Ln(s,e);return Me(s)?Xe(s,t):at.promises.copyFile(s,t)},Dc=async s=>Me(s)?$t(s):at.promises.readFile(s),ct=async(s,e)=>(0,at.createReadStream)(s).pipe(um.Extract({path:e})),Nc=s=>(0,at.statSync)(s).size/1e6});var Wt={};z(Wt,{APPIUM_SESSION_MESSAGE:()=>$c,CLI_MODE:()=>K,MOBILE_APP_SOURCE:()=>Nn,MOBILE_RUN_SKIP_REASON:()=>jc,OPERANDS:()=>Zs,REGION_CONFIG:()=>Jr,X_HEADER_RUNNER_ID:()=>Wc,gridMessages:()=>bt,gridTypes:()=>N,mobileWeb:()=>Uc,runnerStatus:()=>Fc,runnerTestStatus:()=>fe,socketEventTypes:()=>kt,stepResult:()=>Kr,test:()=>Bc,testRunStatus:()=>Qs,testStatus:()=>Ye,timeoutMessages:()=>Pe});var Pe,Qs,Fc,fe,Ye,bt,Uc,Bc,kt,K,N,Kr,Nn,jc,$c,Wc,Jr,Zs,oe=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"},Qs={COMPLETED:"completed"},Fc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},fe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Ye={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},bt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Uc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Bc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},kt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},K={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"},Kr={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"},Nn={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},jc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},$c={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"},Wc="X-Testim-Runner-ID",Jr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"},Zs=(t=>(t.AND="AND",t.OR="OR",t))(Zs||{})});function ei(s,e){var t,r,i,n,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(i=s.browser)==null?void 0:i.toLowerCase()]:(n=s.testConfigNames)!=null&&n.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 _w(){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 ti,fm,Qe,Lw,Dw,Nw,Mw,Fw,Vc,Gc,gm=I(()=>{"use strict";oe();ti=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},fm=s=>Boolean(s.resultId&&s.source==="remote-run"),Qe=(s,e)=>s.testStatus===Ye.QUARANTINE&&!fm(e)&&!e.runQuarantinedTests;Lw=s=>Boolean(s.loginMode),Dw=s=>Boolean(s.tunnelOnlyMode),Nw=s=>Boolean(s.createPrefechedData),Mw=s=>Boolean(s.installLazyDepsMode),Fw=s=>Boolean(s.agentMode),Vc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Gc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Fn(s=0){return Mn.default.duration(s).format("HH:mm:ss.SSS")}function Hc(s=0){return Mn.default.duration(s).asSeconds()}var Mn,hm,Un,ym=I(()=>{"use strict";Mn=R(require("dayjs")),hm=R(require("dayjs/plugin/duration"));Mn.default.extend(hm.default);Un=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 ri,Xr,Zt,bm,Yr,Tm=I(()=>{"use strict";oe();ri=s=>!(!s||"fileName"in s),Xr=(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},Zt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},bm=s=>s===N.TESTIM_TVC,Yr=(s,e)=>bm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function qc(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 wm=I(()=>{"use strict"});var Q={};z(Q,{OSS:()=>Qr,TESTIM_BROWSER_DIR:()=>Vt,buildBasicHeader:()=>gc,calcPercentile:()=>$n,copyDir:()=>dm,delay:()=>pe,doesPathExist:()=>ye,download:()=>$t,downloadAndSave:()=>Xe,extractElementId:()=>Fe,formatTimeoutDuration:()=>Un,getArgsOnRemoteRunFailure:()=>_w,getBrowserInfo:()=>Bw,getCdpAddressForHost:()=>Sr,getCliLocation:()=>yt,getDuration:()=>Fn,getDurationSec:()=>Hc,getEnginesVersion:()=>Mc,getEnvironmentGitBranch:()=>vr,getLinksFromUnescapeHTML:()=>ni,getLocalFileSizeInMB:()=>Nc,getMemorySnapshot:()=>qc,getPlanType:()=>jn,getRunConfigByBrowserName:()=>si,getRunnerVersion:()=>it,getSource:()=>Dn,getSourceAsBuffer:()=>Dc,getSourcePath:()=>Ln,getTestUrl:()=>Ke,getUniqBrowsers:()=>ei,groupTestsByRetries:()=>Kc,guid:()=>se,hasTestPlanFlag:()=>ti,isAgentMode:()=>Fw,isAppFromDevice:()=>ri,isAppFromDeviceDisabled:()=>Yr,isCreatePrefetchedDataMode:()=>Nw,isInstallLazyDepsMode:()=>Mw,isLoginMode:()=>Lw,isMobileProject:()=>Zt,isPromise:()=>Ic,isQuarantineAndNotRemoteRun:()=>Qe,isRemoteRun:()=>fm,isTestimVirtualGrid:()=>bm,isTunnelOnlyMode:()=>Dw,isURL:()=>Me,promiseAbort:()=>Rc,promiseFromCallback:()=>Qt,promiseMap:()=>ie,promiseTimeout:()=>le,removePropertyFromObject:()=>Bn,replaceArgsWithNoDashes:()=>Vc,sanitizeNumberValue:()=>wr,shouldBlockVirtualIosBuild:()=>Xr,spreadObjectToArgs:()=>Gc,unescapeHTML:()=>ii,unzipFile:()=>ct});function wr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function Bw(s){return s=s.toLowerCase(),zc.find(e=>e.browserValue===s)}function si(s,e,t){s=s==null?void 0:s.toLowerCase();let r=zc.find(n=>n.browserName.toLowerCase()===s||s.includes(n.synonyms))||zc[0],i=Qr.find(n=>n.osName==="Windows 10");return e&&(e.platform?i=Qr.find(n=>n.sl.platform===e.platform):e.platformName&&(i=Qr.find(n=>n.sl.platformName===e.platformName))),t&&(t.os_version?i=Qr.find(n=>n.bs.os_version===t.os_version):t.platform&&(i=Qr.find(n=>n.bs.platform===t.platform))),Zr.merge(r,i)}function vr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Bn(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Bn(s[r],e,t))}function Fe(s){return s.ELEMENT||s[Kt]}function jn(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Kc(s=[]){return Zr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((n,o)=>{let a=typeof n.retryCount=="number"?n.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?n.startTime-o.startTime:(n.retryCount??0)-(o.retryCount??0)}),i=Zr.cloneDeep(r.at(-1));return i&&(i.retryTestResults=r,e.push(i)),e},[]).compact().value()}function ii(s){return Rm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function ni(s){return[...Rm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function Sr(s,e){let t=await Promise.resolve().then(()=>(He(),Je));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var Sm,Zr,Em,Im,Uw,Vt,vm,Qr,zc,$n,Rm,F=I(()=>{"use strict";Sm=R(require("os")),Zr=R(require("lodash")),Em=R(require("path")),Im=require("linkedom");Vr();mm();gm();ym();hc();xc();Tm();wm();Uw=Sm.homedir(),Vt=Em.join(Uw,".testim-browser-profile"),vm="133",Qr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],zc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:vm},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:vm},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"}];$n=(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,i)=>r-i),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};Rm=new Im.DOMParser});var Jc={};z(Jc,{$schema:()=>jw,default:()=>Hw,definitions:()=>$w,properties:()=>Gw,required:()=>Vw,type:()=>Ww});var jw,$w,Ww,Vw,Gw,Hw,xm=I(()=>{jw="http://json-schema.org/draft-07/schema#",$w={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}}}},Ww="object",Vw=["entries"],Gw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Hw={$schema:jw,definitions:$w,type:Ww,required:Vw,properties:Gw}});async function Lm(){try{return await le(Wn.promises.readFile(qn()).then(async s=>{let e=await _m;return Kw(e,s)}),3e4)}catch{return{}}}function Kw(s,e){let t=e.slice(0,16),r=e.slice(16),i=Buffer.from(s),n=ts.createDecipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),t),o=n.update(r);return JSON.parse(Buffer.concat([o,n.final()]))}function Ot(s,e,t=qw,r=void 0){return async()=>{if(!Pm)return await s();let i=e;r&&(e+=JSON.stringify(r));let n=await Yc(e);if(n)return oi.debug("cache hit:",{fnName:e}),n;if(oi.debug("cache miss:",{fnName:e}),!km)throw new Error(`Attempted to rebuild cache for ${i}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Jw(e,o,t),o}}async function Yc(s){let t=(await zn)[s];if(!t)return;let{value:r,expiry:i}=t;if(!(i<Date.now())&&r)return r}async function Jw(s,e,t){if(Xc)throw oi.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 zn;r[s]={value:e,expiry:Date.now()+t},Om=new Promise(i=>{Hn=i}),zw(r)}catch{oi.error("failed updating cache")}}async function rs(){let s=await zn;Object.keys(s).forEach(e=>{delete s[e]})}function Dm(s){Pm=s}function Xw(s=!0){km=s}async function Nm(){try{return Xc=!0,await Om}finally{Xc=!1}}function Mm(s){Gn=s,zn=Lm()}var Wn,Vn,ts,Am,oi,Gn,Cm,Hn,Pm,km,Xc,Om,_m,qw,qn,zn,zw,Fm,Um,Ax,Bm,er=I(()=>{"use strict";Wn=R(require("fs")),Vn=R(require("path")),ts=R(require("crypto"));F();Am=require("lodash");W();oi=P("local cache"),Gn=Vn.resolve(yt(),"testim-cache"),Pm=!0,km=!0,Xc=!1,Om=new Promise(s=>{Hn=s}),_m=new Promise(s=>{Cm=s}),qw=1e3*60*60*3,qn=()=>Vn.resolve(Vn.resolve(Gn,"testim.cache"));zn=Lm(),zw=(0,Am.debounce)(async s=>{let e;try{let t=await _m,r=ts.randomBytes(16),i=JSON.stringify(s),n=Buffer.from(t),o=ts.createCipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(i),o.final()]);await ye(Gn)||await Wn.promises.mkdir(Gn,{recursive:!0}),await Wn.promises.writeFile(qn(),a)}catch(t){oi.error("failed saving cache",{err:t}),e=t}Hn(e?{success:!1,error:e}:{success:!0})},200);Fm=Cm,Um=Dm.bind(void 0,!1),Ax=Dm.bind(void 0,!0),Bm=()=>Xw(!1)});function Kn(){return{cliLocation:yt(),userInfo:ss.userInfo(),platform:ss.platform(),release:ss.release()}}var ss,Qc=I(()=>{"use strict";ss=R(require("node:os"));F()});function Yw(s){try{return Jn.resolve(Jn.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 tr(s){let e=Yw(s);return require(e)}var Jn,ai=I(()=>{"use strict";Jn=R(require("path"))});function Qw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Zw(s){return/The "to" argument must be of type string./.exec(s)}function Vm(s,e,t){let r=Qw(s),i=Zw(s);return r||i?(Wm.info("Failed to install package due to insufficient write access",{...Kn(),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 il(s){try{return tr(s)}catch{return!1}}function zm(s,e){return require(li.join(s,`./node_modules/${e}/package.json`)).version}function Km(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=Km(s[e]);if(t)return t}}function Jm(s){let e=require(li.join(s,"package.json"));if(!("exports"in e))return"";let t=Km(e);if(!t)throw new _n(e.name);return t}async function Qn(s,e,t){let r=li.join(s,"npm-shrinkwrap.json"),i=li.join(s,"npm-shrinkwrap-dummy.json"),n=!1;try{try{await ye(r)&&(await sl.promises.rename(r,i),n=!0)}catch{}return await Gm(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw qm(o.stderr,s,e)?new Jr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(n)try{await sl.promises.rename(i,r)}catch{}}}function nl(s,e,t,r,i=!0){return new Promise((n,o)=>{var h,g,y,v;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"];i&&m.push("--prefer-offline");let u="npm";process.platform==="win32"&&(u="npm.cmd",c.shell=!0);let f=(0,Xn.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",b=>{l+=b}),(v=f.stderr)==null||v.on("data",b=>{d+=b}),f.on("close",b=>{var T,w;if(b){i&&nl(s,e,t,r,!1).then(n).catch(o);let E;try{let C=(T=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(d))==null?void 0:T[1],_=(w=/No matching version found for (\S+)@/gm.exec(d))==null?void 0:w[1];C||_?E=`404 Not Found - GET https://registry.npmjs.org/${_??C} - Not found`:qm(d,s)?E=`insufficient write access in location ${s}`:E=`Npm Installation closed with exit code ${b} with error: ${d}`}catch(C){E=`Npm Install closed with exit code ${b}
10
- err: ${C}
11
- stdout: ${l} stderr: ${d}`}Hm.info(`Npm Install closed with exit code ${b}`,{message:E,stderr:d}),o(new Pt(E))}else n(l)}),setTimeout(()=>{try{f.kill()}finally{o(new ce)}},r)})}async function Ym(){try{return(await Gm("npm -v")).stdout.trim()}catch{return""}}var sl,li,Vm,Xn,Gm,Hm,as=I(()=>{"use strict";sl=R(require("fs")),li=R(require("path"));F();Vm=require("util"),Xn=require("child_process");W();rl();ci();X();Gm=(0,Vm.promisify)(Xn.exec),Hm=P("cli-service")});var U,Qm,Zm,ef,rv,sv,iv,Xm,Zn,al,O,de=I(()=>{"use strict";U=R(require("rox-node")),Qm=R(require("node-fetch")),Zm=require("eventsource");W();F();oe();ef=P("FeatureFlagsService"),rv=!Ve&&!0&&!Ud,sv=2e4,iv=60*60*24,Xm=["labs","disabled","enabled"],Zn=class extends U.default.RoxString{constructor(e="disabled"){super(e,Xm)}getValue(){let e=super.getValue();return Xm.includes(e)?e:(ef.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},al=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 Zn("labs"),highSpeedMode:new Zn,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,enableAppium2pCloudy: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("")},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,i;if(!rv)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,c)=>(0,Qm.default)(a,{...c,agent:o}),i=function(a){return new Zm.EventSource(a,{fetch:r})}}let n={fetchIntervalInSec:iv,fetchFunction:r,eventSourceImpl:i};return le(U.default.setup(Md,n),sv).catch(o=>ef.error("failed to get feature flag status",o))}},O=new al});var nf={};z(nf,{install:()=>ov,isReady:()=>cv,start:()=>av});var tf,rf,sf,ll,cl,nv,ov,av,cv,of=I(()=>{"use strict";tf=R(require("fkill")),rf=R(require("p-retry"));as();He();F();ci();de();sf="chromedriver",ll=9515,cl=`http://localhost:${ll}/wd/hub`,nv=[`--port=${ll}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],ov=async()=>{let s=O.flags.chromedriverCdnBinariesUrl.getValue(),e=Me(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await Qn(yt(),`${sf} --detect_chromedriver_version ${e}`)},av=async()=>{process.env.NODE_OPTIONS="",await(0,tf.default)(`:${ll}`,{silent:!0}),await tr(sf).start(nv,!0)},cv=async({chromeBinaryLocation:s})=>{await(0,rf.default)(async()=>{var i;let e=await we(`${cl}/status`);if(!((i=e==null?void 0:e.value)!=null&&i.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Ge({url:`${cl}/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 Ys(`${cl}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var pi={};z(pi,{getSessionPlayerFolder:()=>ml,prepareChromeDriver:()=>ui,prepareCustomExtension:()=>pl,prepareExtension:()=>dl,preparePlayer:()=>Rr});async function pl(s,e=!1){if(!s)return;if(Me(s)){let i=cs.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await lv(s)>ul&&!e)throw new x(af);return await Ye(s,i),i}let t=cs.resolve(s);if(!lf.existsSync(t))throw new x(`Failed to find custom extension in location: ${t}`);if(Bc(t)>ul&&!e)throw new x(af);return t}async function lv(s){let e=(He(),ze(Je));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw eo.warn("failed to download custom extension",{err:t}),new x(`Failed to download custom extension from location: ${s}`)}}function dl(s){eo.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Ln(t)}));return Ot(()=>ie(e,({location:t,path:r})=>Nn(t,r)),"prepareExtension",pf,e)()}async function ui(s={},e={},t=!1){let i=require("ora")("Starting Driver").start(),n=await Promise.resolve().then(()=>(of(),nf));try{await n.install(),await n.start(),t||await n.isReady(e),i.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof Jr||(eo.error(a,{...s,...Jn(),error:(0,uf.serializeError)(o)}),console.log(`
9
+ `),!0):!1}function el(s){try{return tr(s)}catch{return!1}}function Gm(s,e){return require(ci.join(s,`./node_modules/${e}/package.json`)).version}function Hm(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=Hm(s[e]);if(t)return t}}function qm(s){let e=require(ci.join(s,"package.json"));if(!("exports"in e))return"";let t=Hm(e);if(!t)throw new On(e.name);return t}async function Yn(s,e,t){let r=ci.join(s,"npm-shrinkwrap.json"),i=ci.join(s,"npm-shrinkwrap-dummy.json"),n=!1;try{try{await ye(r)&&(await Zc.promises.rename(r,i),n=!0)}catch{}return await $m(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw Vm(o.stderr,s,e)?new qr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(n)try{await Zc.promises.rename(i,r)}catch{}}}function tl(s,e,t,r,i=!0){return new Promise((n,o)=>{var h,g,y,v;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"];i&&m.push("--prefer-offline");let u="npm";process.platform==="win32"&&(u="npm.cmd",c.shell=!0);let f=(0,Xn.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",b=>{l+=b}),(v=f.stderr)==null||v.on("data",b=>{d+=b}),f.on("close",b=>{var T,w;if(b){i&&tl(s,e,t,r,!1).then(n).catch(o);let E;try{let A=(T=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(d))==null?void 0:T[1],_=(w=/No matching version found for (\S+)@/gm.exec(d))==null?void 0:w[1];A||_?E=`404 Not Found - GET https://registry.npmjs.org/${_??A} - Not found`:Vm(d,s)?E=`insufficient write access in location ${s}`:E=`Npm Installation closed with exit code ${b} with error: ${d}`}catch(A){E=`Npm Install closed with exit code ${b}
10
+ err: ${A}
11
+ stdout: ${l} stderr: ${d}`}Wm.info(`Npm Install closed with exit code ${b}`,{message:E,stderr:d}),o(new Pt(E))}else n(l)}),setTimeout(()=>{try{f.kill()}finally{o(new ce)}},r)})}async function zm(){try{return(await $m("npm -v")).stdout.trim()}catch{return""}}var Zc,ci,jm,Xn,$m,Wm,is=I(()=>{"use strict";Zc=R(require("fs")),ci=R(require("path"));F();jm=require("util"),Xn=require("child_process");W();Qc();ai();Y();$m=(0,jm.promisify)(Xn.exec),Wm=P("cli-service")});var U,Jm,Xm,Ym,ev,tv,rv,Km,Qn,sl,O,de=I(()=>{"use strict";U=R(require("rox-node")),Jm=R(require("node-fetch")),Xm=require("eventsource");W();F();ae();Ym=P("FeatureFlagsService"),ev=!Ve&&!0&&!Md,tv=2e4,rv=60*60*24,Km=["labs","disabled","enabled"],Qn=class extends U.default.RoxString{constructor(e="disabled"){super(e,Km)}getValue(){let e=super.getValue();return Km.includes(e)?e:(Ym.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},sl=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 Qn("labs"),highSpeedMode:new Qn,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("")},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,i;if(!ev)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,c)=>(0,Jm.default)(a,{...c,agent:o}),i=function(a){return new Xm.EventSource(a,{fetch:r})}}let n={fetchIntervalInSec:rv,fetchFunction:r,eventSourceImpl:i};return le(U.default.setup(Dd,n),tv).catch(o=>Ym.error("failed to get feature flag status",o))}},O=new sl});var tf={};z(tf,{install:()=>iv,isReady:()=>ov,start:()=>nv});var Qm,Zm,ef,nl,il,sv,iv,nv,ov,rf=I(()=>{"use strict";Qm=R(require("fkill")),Zm=R(require("p-retry"));is();He();F();ai();de();ef="chromedriver",nl=9515,il=`http://localhost:${nl}/wd/hub`,sv=[`--port=${nl}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],iv=async()=>{let s=O.flags.chromedriverCdnBinariesUrl.getValue(),e=Me(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await Yn(yt(),`${ef} --detect_chromedriver_version ${e}`)},nv=async()=>{process.env.NODE_OPTIONS="",await(0,Qm.default)(`:${nl}`,{silent:!0}),await tr(ef).start(sv,!0)},ov=async({chromeBinaryLocation:s})=>{await(0,Zm.default)(async()=>{var i;let e=await we(`${il}/status`);if(!((i=e==null?void 0:e.value)!=null&&i.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Ge({url:`${il}/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 Xs(`${il}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var ui={};z(ui,{getSessionPlayerFolder:()=>ll,prepareChromeDriver:()=>li,prepareCustomExtension:()=>al,prepareExtension:()=>cl,preparePlayer:()=>Ir});async function al(s,e=!1){if(!s)return;if(Me(s)){let i=ns.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await av(s)>ol&&!e)throw new x(sf);return await Xe(s,i),i}let t=ns.resolve(s);if(!of.existsSync(t))throw new x(`Failed to find custom extension in location: ${t}`);if(Nc(t)>ol&&!e)throw new x(sf);return t}async function av(s){let e=(He(),ze(Je));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Zn.warn("failed to download custom extension",{err:t}),new x(`Failed to download custom extension from location: ${s}`)}}function cl(s){Zn.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Ln(t)}));return Ot(()=>ie(e,({location:t,path:r})=>Dn(t,r)),"prepareExtension",cf,e)()}async function li(s={},e={},t=!1){let i=require("ora")("Starting Driver").start(),n=await Promise.resolve().then(()=>(rf(),tf));try{await n.install(),await n.start(),t||await n.isReady(e),i.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof qr||(Zn.error(a,{...s,...Kn(),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)`)),i.fail(a),o}}async function uv(){let s=`${Jt}/sessionPlayer_LATEST_RELEASE`;return(await $t(s)).body.toString("utf8")}async function pv(s,e){if(!Me(s)||Me(s)&&e||Ve)return s;let t=await uv();return`${s}-${t}`}function ml(){let s=yt();return cs.resolve(s,"testim-bin")}function dv(){let s=ml();return cs.resolve(s,"sessionPlayer.zip")}async function df(s,e,t=!1){try{return await Nn(s,e),await ct(e,ml())}catch(r){if(t)throw r;return await df(s,e,!0)}}async function Rr(s,e){eo.info("prepare player",{location:s,canary:e});let t=dv();return Ot(async()=>{let r=await pv(s,e);return await df(r,t),{}},"preparePlayer",pf,[s,e,t])()}var cf,lf,cs,uf,eo,pf,ul,af,di=I(()=>{"use strict";cf=R(require("ms")),lf=R(require("node:fs")),cs=R(require("node:path"));oe();er();uf=require("serialize-error");W();rl();X();F();eo=P("prepare runner and testim start"),pf=(0,cf.default)("0.5 day"),ul=16,af=`The size of the custom extension is more than ${ul}MB`});function mv(){let s=mi.type().toLowerCase();return s==="darwin"?mi.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?mi.arch()==="x64"?"win64":"win32":"linux"}async function ro(){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(fi,10)>591479?"chrome-win":"chrome-win32",i={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},n={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]}/${fi}/${i[s]}.zip`,a=to.join(fl,i[s]),c=`${a}.zip`,l=to.join(a,n[s]);if(await ye(l))return l;if(!await ye(c)){let m=(0,gl.default)("Downloading Chromium").start();try{await mf.promises.mkdir(fl),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,gl.default)("Extracting Chromium").start();try{await ct(c,fl)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),l}var mf,mi,to,gl,fi,fl,hl=I(()=>{"use strict";mf=R(require("fs")),mi=R(require("os")),to=R(require("path")),gl=R(require("ora"));X();F();fi="1000968",fl=to.join(Vt,`chrome-${fi}`)});async function hf(s,e){return xr=s,wl=e,await yl()}function yf(s,e){xr=e.projectId,wl=e.token,gi=e.userAccessKey,lt=s.token,yi=vl(lt),bi=s.refreshToken,bl=s.ngrokToken,Tl=s.isNgrokWhitelisted,ff=e.publicIp,gf=e.initializedFromCache}function gv(s=xr,e=wl){return Ot(()=>(hi.info("request to get cli token from server"),Ge({url:`${he()}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",fv*10,{projectId:s,token:e})()}async function hv(){hi.info("request to refresh JWT cli token from server");let s=await Ge({url:`${he()}/auth/refreshToken`,body:{token:lt,refreshToken:bi}});return lt=s.token,yi=vl(lt),s.refreshToken&&(bi=s.refreshToken),lt}async function yl(){try{let s=await gv();return hi.info("successfully get cli token from server"),lt=s.token,yi=vl(lt),bi=s.refreshToken,bl=s.ngrokToken,Tl=s.isNgrokWhitelisted,lt}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."):(hi.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:xr}),new x(`While trying to retrieve CLI token, caught error: ${s}`))}}function vl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function _t(){if(!yi)return yl();let s=O.flags.accessTokenExpiryMargin.getValue();if(yi<Date.now()+4*s)try{return await hv()}catch(e){return hi.error("failed to refresh token, executing fallback",e),yl()}return lt}function so(){return bi}function Cr(){return lt?{uid:require("jsonwebtoken").decode(lt).id,ngrokToken:bl,isNgrokWhitelisted:Tl}:{}}async function io(){if(!gi||!xr)return;if(await Sl({userAccessKey:gi,projectId:xr}))return gi;let e=`user access key "${gi}" is invalid for project "${xr}"`;throw new x(e)}function no(){return ff}function oo(){return gf}var hi,lt,yi,bi,bl,Tl,xr,wl,gi,ff,gf,fv,ut=I(()=>{"use strict";oe();He();er();X();W();ge();de();hi=P("testim-custom-token"),xr=null,wl=null,fv=5*60*1e3});function yv(s){if(s.protocol)return s.protocol;if([D.TESTIM_PRIVATE,D.TESTIM,D.BROWSERSTACK,D.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([D.TESTIM_ENTERPRISE,D.TESTIM_LAMBDATEST,D.DEVICE_FARM].includes(s.type)){let e=bf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function bv(s){let e=bf.exec(s);return e==null?void 0:e[3]}function co(s){var w,E,C,_,B,V,S,A,N,j,H;let e=s&&bv(s.host),t=s.port,r=s.path,i=s&&yv(s),n=s.token,o=s.slotId,a=(w=s.hybrid)==null?void 0:w.tunnel,c=(E=s.external)==null?void 0:E.user,l=(C=s.external)==null?void 0:C.key,d=s.type,m=d===D.HYBRID?a&&((V=(B=(_=s.hybrid)==null?void 0:_.external)==null?void 0:B[s.hybrid.tunnel])==null?void 0:V.user):c,u=d===D.HYBRID?a&&((N=(A=(S=s.hybrid)==null?void 0:S.external)==null?void 0:A[s.hybrid.tunnel])==null?void 0:N.key):l,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(j=s.mobileTokens)==null?void 0:j.androidToken,v=(H=s.mobileTokens)==null?void 0:H.iosToken,b=s.apiUrl,T=s.isSupportGrid;return{host:e,port:t,path:r,protocol:i,accessToken:n,slotId:o,gridId:h,tunnel:a,user:c,key:l,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:v,apiUrl:b,isSupportGrid:T}}async function wv(s,e,t,r,i,n){var a;let o;try{o=await n()}catch(c){throw pt.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(bt.UNKNOWN)}if(pt.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw pt.error("invalid response - get grid",{res:o}),new Error(bt.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,Sf(i));let c=co(o.grid);return Tv(t,e,c.gridId,c.slotId,r,c.isSupportGrid),c}throw o.code==="not-found"?new nt(bt.NOT_FOUND):o.code==="no-available-slot"?new Xt(`Failed to run test on ${r} - concurrency limit reached`):(pt.error("invalid code error response - get grid",{res:o}),new nt(bt.UNKNOWN))}function wf(s){return Al(s)}async function vf(s,e,t){let i=(t||await wf(s)).find(n=>n._id===e);if(!i)throw new x(`Failed to find grid id: ${e}`);return co(i)}async function vv(s,e,t){let i=(t||await wf(s)).find(n=>(n.name||"").toLowerCase()===e.toLowerCase());if(!i)throw new x(`Failed to find grid name: ${e}`);return co(i)}async function El(s,e){let t=Ti[s];if(!t)return;let{slotId:r,gridId:i,browser:n,companyId:o,isSupportGrid:a}=t;if(delete Ti[s],!a){if(!r){pt.warn("failed to find grid slot id",{projectId:e});return}pt.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:i,browser:n});try{await Rl(o,e,r,i,n)}catch(c){pt.error("failed to release slot",{projectId:e,err:c})}}}async function Sv(s){let e=Object.values(Ti).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid)try{await Il(s,e)}catch(t){pt.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}function Ev(s){Tf=global.setInterval(Sv,1e4,s)}async function Iv(s){let e=Object.keys(Ti);if(e.length){pt.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>El(Number(t),s))}catch(t){pt.error("failed to release all slots",{err:t,projectId:s})}}}async function Rv(s){await Iv(s),clearInterval(Tf)}function xv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function Cv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function Sf(s){let t=(()=>ao.isEmpty(s.testobjectSauce)?ao.isEmpty(s.saucelabs)?ao.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:i,path:n,protocol:o}=s,a=xv(t,s),c=Cv(t,s);return{host:r,port:i,path:n,protocol:o,type:t,user:c,key:a,gridId:se()}}async function Ef(s,e){let t=s.company.companyId;return await vf(t,e.gridId,s.allGrids)}async function If(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:i,localTmaUrl:n,useChromeLauncher:o,gridId:a,grid:c}=s;if(i||o||n)return{mode:"local"};if(r)return Sf(s);let l=t==null?void 0:t.companyId;if(a)return vf(l,a,e);if(c)return vv(l,c,e);if(ri(s)||s.tunnelOnlyMode){pt.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new nt("Missing host or grid configuration")}async function Rf(s,e,t,r,i){let{host:n,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 wv(o,h,r,s,t,()=>Cl({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:n,testResultId:i}))}var ao,pt,Ti,bf,Tf,Tv,wi,xf,ls=I(()=>{"use strict";ao=R(require("lodash"));ge();W();F();ae();X();pt=P("grid-service"),Ti={},bf=/(^(https?):\/{2})?(.*)/,Tf=null;Tv=(s,e,t,r,i,n)=>{Ti[s]={gridId:t,companyId:e,slotId:r,browser:i,isSupportGrid:n}};wi={start:Ev,end:Rv};xf=async(s={},e={},t={},r={},i={})=>{var g,y,v;let{company:{companyId:n}={},project:o}=s,{gridId:a,type:c}=e,l=s.browser||t.browserValue,d=Boolean(s.tunnel),{maxRetries:m,currentRetry:u}=i;if(!a||!c||((c===D.TESTIM_LAMBDATEST||c===D.LAMBDATEST)&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e,n,o)),c!==D.HYBRID||!n||!l||!m||!u))return e;let f=await xl({companyId:n,gridId:a,maxRetries:m,currentRetry:u,browser:l,usingTunnel:d});pt.info("handling hybrid grid",{response:f,companyId:n});let h=co({...e,...f.connectionDetails,provider:f.provider});return f.provider!=="lambdatest"&&((y=r.disable)==null||y.call(r)),f.provider==="lambdatest"&&await((v=r.enableIfNeeded)==null?void 0:v.call(r,h,n,o)),h}});function Si(){return lo||"master"}function Cf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){lo="master";return}if(s!=null&&s.isArchived)throw new x(`Branch ${s.branch} is archived, run aborted.`);if(s){lo=s.branch||s;return}lo=e?"master":void 0}var lo,Pl=I(()=>{"use strict";X()});function Of(s){Ve||(s!=null&&s.userId||(s={anonymousId:"runnerId"}),kf.identify(s))}function dt(s,e){return us("ci",s,e)}function us(s,e,t){if(Ve)return;let r=s?{userId:s}:{anonymousId:"runnerId"};kf.track(Object.assign(r,{event:e,properties:t}))}var Pf,kf,ps=I(()=>{"use strict";oe();Pf=require("@segment/analytics-node"),kf=new Pf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1})});var _f={};z(_f,{isCi:()=>ds});var ds,uo=I(()=>{"use strict";ds=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Lf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Nf({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:n,companyName:o,projectName:a,companyPlan:c,source:l,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Lf({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:n,companyName:o,projectName:a,companyPlan:c,source:Df(l,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);dt("test-run-ci",y)}function Mf({executionId:s,projectId:e,testId:t,resultId:r,result:i,ucid:n,companyId:o,companyName:a,projectName:c,companyPlan:l,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:v}){try{let b=Lf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:i.wasMockNetworkActivated,source:Df(d,m),isStartUp:h,projectType:g,gridType:v,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(i.success){dt("test-run-ci-success",b);return}dt("test-run-ci-fail",{...b,failureReason:i.failureReason})}catch(b){f.error("failed to update test end analytics",{err:b})}}function Ff(s){dt("batch-run-ci",s)}var Df,kl=I(()=>{"use strict";ps();uo();Df=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ds&&e?"ci-with-user":ds?"ci":e?"cli-with-user":s});var Ol,ue,Bf=I(()=>{"use strict";Ol=class{static colorString(e,t){return`${e}${t}${Ol.Reset}`}},ue=Ol;ue.Reset="\x1B[0m",ue.Bright="\x1B[1m",ue.Dim="\x1B[2m",ue.Underscore="\x1B[4m",ue.Blink="\x1B[5m",ue.Reverse="\x1B[7m",ue.Hidden="\x1B[8m",ue.FgBlack="\x1B[30m",ue.FgRed="\x1B[31m",ue.FgGreen="\x1B[32m",ue.FgYellow="\x1B[33m",ue.FgBlue="\x1B[34m",ue.FgMagenta="\x1B[35m",ue.FgCyan="\x1B[36m",ue.FgWhite="\x1B[37m",ue.FgGray="\x1B[90m",ue.BgBlack="\x1B[40m",ue.BgRed="\x1B[41m",ue.BgGreen="\x1B[42m",ue.BgYellow="\x1B[43m",ue.BgBlue="\x1B[44m",ue.BgMagenta="\x1B[45m",ue.BgCyan="\x1B[46m",ue.BgWhite="\x1B[47m",ue.BgGray="\x1B[100m"});var Ii,_l,Av,Dl,Pv,po,mo,fo,go,ho,yo=I(()=>{"use strict";F();ae();Ii=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===fe.FAILED},_l=s=>{let{status:e}=s;return e===fe.ABORTED},Av=s=>{let{status:e}=s;return e===fe.PASSED},Dl=s=>s.runnerStatus===$c.SKIPPED,Pv=s=>s.testStatus===Xe.EVALUATING,po=(s,e)=>Object.values(s).filter(t=>{var r,i;return Dl(t)&&(Qe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((i=t.mobile)==null?void 0:i.isAppForIosVirtualDevice))}).length,mo=s=>Object.values(s).filter(e=>Ii(e)&&Pv(e)).length,fo=s=>Object.values(s).filter(Ii),go=s=>Object.values(s).filter(Av),ho=s=>Object.values(s).filter(_l)});function Ov(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Ll,bo,kv,To,jf=I(()=>{"use strict";Ll=R(require("lodash"));W();yo();bo=P("debug-reporter"),kv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],To=class{constructor(e){this.options=e}onTestStarted(e,t){bo.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},i=r.provider,n=r.host,o=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;bo.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:i,host:n,failedGetBrowserAttempts:c,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Ll.default.omit(this.options,kv),company:Ll.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,i,n,o,a){let c=Ov(process.argv);bo.info("Test Plan Started",{executionId:n,testPlanName:i,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,i,n){let o=go(e).length,a=Object.keys(e).length-o;bo.info("Test Plan Finished",{executionId:i,testPlanName:t,isAnonymous:n,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Nl,Dt,Ri=I(()=>{"use strict";ae();Nl=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===D.DEVICE_FARM}},Dt=new Nl});var Fl={};z(Fl,{Reporter:()=>_v});var sr,xi,Ar,wo,$f,Ml,_v,Ul=I(()=>{"use strict";sr=R(require("chalk")),xi=R(require("lodash"));F();ae();Ri();yo();Ar={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:wo}=Wt,$f="device",Ml=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})`,i=`url: ${sr.default.underline(Ke(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${i}`.trim())}onTestFinished(e,t){let r=e.success?fe.PASSED:fe.FAILED,i=`(${e.testId})`,n=Ar[e.success?"success":"error"];console.log(n(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${i} duration: ${Un(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let i=Ke(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${i}`});console.log(Ar.error("Failed runs are:")),console.log(Ar.error(t.join(`
18
- \r`)))}onTestPlanFinished(e,t,r,i,n){let o=fo(e),a=go(e),c=ho(e),l=a.length,d=c.length,m=o.length,u="",f="";if(Dt.isTestStatusEnabled){let b=mo(e);u=` FAILED-EVALUATING: ${b}`,m-=b,f=` SKIPPED: ${po(e,this.options)}`}let h=this.buildTestPlanName(n,t),g,y=Ar[m?"error":"success"],v=`PASSED: ${l} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Un(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${v} (Execution ID: ${i})`:g=`Test plan${h} completed ${v} (${i})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=xi.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,i=xi.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,n=xi.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=xi.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[n,i,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,i,n,o,a){let c=u=>{u.forEach((f,h)=>{var b;let g=(b=f.testData)!=null&&b.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`,v="";f.testOptimization?v=` [${f.testOptimization.reason}]`:Qe(f,this.options)&&(v="-quarantine"),console.log(" ",h+1,":",`${f.name}${v}`,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,i)} test plan with ${m} (${n})`),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,i=this.options.mode===wo.APPIUM?$f:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(i)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let i=r===wo.APPIUM?$f:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${i} to run ${sr.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 i=this.options.grid||this.options.gridId,n=this.options.mode===wo.APPIUM?"device":"browser";if(i)console.log(Ar.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${n} from the grid ${i}`));else if(this.options.useLocalChromeDriver)console.log(Ar.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===wo.APPIUM?"Appium":"Selenium";console.log(Ar.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},_v=Ml});var $l={};z($l,{Reporter:()=>Uv});function Dv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function Lv(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 Nv(s){return`${s.visitedUrlsJson||""}`}async function Mv(s,e,t,r,i,n){function o(u){let f=Ke(s,t,u.testId,u.resultId,r),h={$:{name:Dv(u),classname:i,time:Jc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(Ii(u)||_l(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=Ii(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Dl(u)&&Qe(u,n)&&Dt.isTestStatusEnabled&&(h.skipped={}),n.urls&&(h["visited-urls-list"]=Lv(u),h["visited-urls-json"]=Nv(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},b={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(y),failures:d(y),timestamp:c(e)};if(Dt.isTestStatusEnabled){b.skipped=po(y,n);let T=mo(y);b.failures-=T,b["failure-evaluating"]=T}return{$:b,testcase:Object.keys(y).map(T=>o(y[T]))}}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 fo(u).length+ho(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new jl.Builder().buildObject(m)}catch(u){return Fv(u)}}function Fv(s){let e=new jl.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 jl,Wf,Bl,Uv,Wl=I(()=>{"use strict";jl=R(require("xml2js"));F();Wf=require("fs");Ri();yo();Bl=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,i=await Mv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Wf.promises.writeFile(t,i),console.log("JUnit XML file saved to",t),e}catch(n){return console.error("could not save report file",t,n),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};Uv=Bl});var Vf={};z(Vf,{Reporter:()=>Bv});function ms(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 Vl,Gl,Bv,Gf=I(()=>{"use strict";W();Vl=P("team-city-reporter");Gl=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",i=`${e.name} (${e.testId})${r}`;return ms(i)}onTestStarted(e,t,r,i){if(r){Vl.debug("skip report test started because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testStarted name='${n}' captureStandardOutput='true' flowId='${i}']`)}onTestFailed(e,t,r,i,n,o){if(n){Vl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ms(t)}' details='${ms(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Vl.debug("skip report test finished because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testFinished name='${i}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let i=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${i}' message='${ms(r)}']`)}onTestPlanStarted(e,t,r,i){console.log(`##teamcity[testSuiteStarted name='${ms(i)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ms(t)}']`)}},Bv=Gl});var Hf={};z(Hf,{Reporter:()=>jv});var Hl,jv,qf=I(()=>{"use strict";Hl=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,i,n){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:n}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},jv=Hl});function So(s){let{platform:e}=process;e==="win32"?(0,vo.exec)(`start chrome ${s}`):e==="darwin"?(0,vo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,vo.exec)(`google-chrome ${s}`)}var vo,ql=I(()=>{"use strict";vo=require("child_process")});var zf={};z(zf,{Reporter:()=>$v});var zl,$v,Kf=I(()=>{"use strict";F();ql();zl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=Ke(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return So(t)}},$v=zl});var Kl,Z,Lt=I(()=>{"use strict";jf();Kl=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 To(e)),r===void 0||r.length===0){let{Reporter:i}=await Promise.resolve().then(()=>(Ul(),Fl));if(this.reporters.push(new i(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:n}=await Promise.resolve().then(()=>(Wl(),$l));this.reporters.push(new n(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Gf(),Vf)),r.includes("console")&&Promise.resolve().then(()=>(Ul(),Fl)),r.includes("junit")&&Promise.resolve().then(()=>(Wl(),$l)),r.includes("json")&&Promise.resolve().then(()=>(qf(),Hf)),r.includes("chrome")&&Promise.resolve().then(()=>(Kf(),zf))])).forEach(n=>{n&&this.reporters.push(new n.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,i,n){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,i,n]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var n;let i=t==null?void 0:t(...r);for(let o of this.reporters)await((n=o[e])==null?void 0:n.call(o,...i||r))}}},Z=new Kl});async function Jl(s,e,t){let r=fs[s];if(!r)return;let{slotId:i}=r;if(delete fs[s],!i){Tt.warn("failed to find slot slot id",{companyId:e,workerId:s});return}Tt.info("release slot id",{companyId:e,slotId:i});try{await Xl(e,t,i)}catch(n){Tt.error("failed to release slot",{companyId:e,err:n})}}async function Wv(s,e){let t=Object.values(fs).filter(Boolean);if(t.length!==0)try{await Zl(s,e,t)}catch(r){Tt.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}function Vv(s,e){Jf=global.setInterval(()=>Wv(s,e),1e4)}async function Gv(s,e){let t=Object.keys(fs);if(t.length){Tt.warn("not all slots released before end runner flow",{companyId:s});try{await ie(t,r=>Jl(Number(r),s,e))}catch(r){Tt.error("failed to release all slots",{err:r,companyId:s})}}}async function Hv(s,e){await Gv(s,e),clearInterval(Jf)}async function Xf(s,e,t){let r;try{r=await Yl(s,e)}catch(i){throw Tt.error("failed to get slot",{companyId:s,err:i}),new Error(bt.UNKNOWN)}if(Tt.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw Tt.error("invalid response - get slot",{res:r}),new Error(bt.UNKNOWN);if(r.status==="success")return Yf(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new nt(bt.NOT_FOUND):r.code==="no-available-slot"?new Xt("Failed to run test - concurrency limit reached"):(Tt.error("invalid code error response - get slot",{res:r}),new nt(bt.UNKNOWN))}async function Qf(s,e,t,r){let i=fs[r];if(!i)throw new Error("slot not found");Object.assign(i,t),Yf(r,i),await Ql(s,e,i),Tt.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var Tt,fs,Jf,Yf,Ci,gs=I(()=>{"use strict";ge();W();F();ae();X();Tt=P("slot-service"),fs={},Jf=null,Yf=(s,e)=>{fs[s]=e};Ci={start:Vv,end:Hv}});function eg(s,e=process){async function t(r){await le(ie(Zf,async i=>i()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Pi.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 i;if(Pi.fatal("Caught unhandled promise rejection",r),!((i=r==null?void 0:r.message)!=null&&i.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Pi.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",i=new Error(r);throw Pi.error(r),t(i),i}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",i=new Error(r);throw Pi.error(r),t(i),i}),e.once("exit",r=>{s(r)})}function hs(s){Zf.push(s)}var Pi,Zf,ki=I(()=>{"use strict";W();F();Pi=P("process-handler"),Zf=[]});var ig={};z(ig,{installAllLazyDependencies:()=>Jv,lazyRequire:()=>mt});async function mt(s,e={}){let t=il(s);if(t)return t;let r;e.silent||(r=(0,tg.default)(`Installing ${s} before first usage...`).start());try{let i=await Kv(s);return r&&r.succeed(),i}catch(i){zv.warn("failed to install dependency lazily",{dependency:s,err:i});let n=sg(s),o=`${s}@${n}`,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),i}}async function Kv(s){return ys.has(s)||(ys.set(s,rg(s)),ys.get(s).catch(()=>{ys.delete(s)})),ys.get(s)}async function rg(s){let e=il(s);if(e)return e;let t=sg(s),r=`${s}@${t}`;return await Qn(yt(),r),tr(s)}async function Jv(){let s=Object.keys(vc);for(let e of s)await rg(e)}function sg(s){let e=Object.entries(vc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var tg,zv,ys,Oi=I(()=>{"use strict";tg=R(require("ora"));as();W();F();En();ci();zv=P("lazy-require"),ys=new Map});var ng,Eo,og=I(()=>{"use strict";ng=require("istanbul-lib-report"),Eo=class extends ng.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 ag,cg,lg,_i,wt,ug,Io,eu,pg,Yv,dg,mg,Xv,Qv,fg,Zv,eS,tS,rS,sS,gg,hg=I(()=>{"use strict";ag=R(require("ora")),cg=R(require("dayjs")),lg=R(require("test-exclude")),_i=R(require("fs")),wt=R(require("path")),ug=R(require("istanbul-reports")),Io=R(require("istanbul-lib-report"));ge();X();F();W();Oi();og();eu=P("test-run-status"),pg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Yv=s=>!!pg(s).search,dg=s=>s?pg(s).pathname.substring(1):"",mg=(s,e)=>{let t=dg(e);return!new lg.default({relativePath:!1,include:s}).shouldInstrument(t)},Xv=s=>s.substring(0,s.indexOf("?")),Qv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await mt("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)},fg=(s,e)=>`${wt.resolve(s,dg(e))}.js`,Zv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async i=>{if(!i)return;let n=i.toObject();await ie(n.sources,async(o,a)=>{if(mg(r,o))return;let c=fg(e,o);await _i.promises.mkdir(wt.parse(c).dir,{recursive:!0}),await _i.promises.writeFile(c,n.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":(Yv(e)&&(e=Xv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=wt.dirname(this.getPath(s));return wt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},tS=async(s,e,t,r)=>{let{codeCoverageReporter:i}=s,n={},o=Io.createContext({dir:t,coverageMap:e,watermarks:Io.getDefaultWatermarks(),sourceFinder:a=>{try{let c=fg(r,a);return _i.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new Eo({appendToObject:n}).execute(o),Array.isArray(i)&&i.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:eS}),ug.create(a,c).execute(o)}),n},rS=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:i}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await mt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>mg(i,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},sS=async(s,e)=>{let{mergeProcessCovs:r}=await mt("@bcoe/v8-coverage"),i={result:[]},n=new Map,a=(await ru(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Di(c,9e4);await ie(l,async d=>{if(!n.has(d.url)){let m=d.text;d.sourceUrl&&(n.set(d.url,"TEMP"),m=await tu(d.sourceUrl)),n.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,i=r([i,{result:[d]}])})},{concurrency:20}),{covUrlMap:n,mergedCoverages:i}},gg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;eu.info("start js coverage process");let i=(0,ag.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),n=wt.resolve(s.codeCoverageReportPath||"./coverage"),o=wt.resolve(n,`.js/${(0,cg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?wt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([mt("istanbul-lib-coverage"),sS(s.project,r)]);if(l.result.length===0){i.fail("Failed to report coverage information - js code coverage is empty");return}eu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),u={};await ie(l.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:v}=d.get(h),b=await Qv({sourceMapType:v,source:y,sourceMapDir:a});u[h]=b;let T=await rS(s,{source:y,sourceMap:b,functions:g});m.merge(T)}),await Zv(s,o,u);let f=await tS(s,m,n,o);return i.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof x?i.fail(`${l}, missing arg: ${c.message}`):i.fail(l),eu.error(l,{err:c})}}});var yg={};z(yg,{SELENIUM_PERF_MARKS:()=>Oe,SeleniumPerfStats:()=>Pr});var Oe,iS,Pr,bs=I(()=>{"use strict";F();Oe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},iS=["ALL",...Object.values(Oe)],Pr=class{constructor(){this.marks=Object.fromEntries(iS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();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`,Wn(r,50)],[`${t}_P95`,Wn(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var vg={};z(vg,{initServer:()=>aS,mapFilesToLocalDrive:()=>iu});function iu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Ro[t.id]?{screenshot:Ro[t.id]}:{})),Object.keys(xo).forEach(t=>{s.assets||={},s.assets[wg[t]]=xo[t]}),s.assets||={},s.assets.screenshots=Object.values(Ro)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function aS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await mt("multer"),i=typeof t=="string"?t:nS;await su.promises.mkdir(i,{recursive:!0});let n=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=Li.join(i,m.testResultId);try{await su.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=Li.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,Tg.default)();o.disable("x-powered-by"),o.post("/",n.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(Ro[d.stepId]=c.file.path),d.testResultId&&oS.includes(d.subType)&&(xo[d.subType]||=[],xo[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 su,bg,Li,Tg,nS,Ro,xo,wg,oS,nu=I(()=>{"use strict";su=R(require("fs")),bg=R(require("os")),Li=R(require("path")),Tg=R(require("express"));X();Oi();nS=Li.join(bg.tmpdir(),"testim/rca/"),Ro={},xo={},wg={"test-log":"consoleLogs","har-file":"networkLogs"},oS=Object.keys(wg)});var ir,ou,Ni,Sg=I(()=>{"use strict";ir=R(require("lodash"));F();W();ou=P("override-test-data-builder"),Ni=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return ir.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)&&!ir.isEmpty(t.overrideTestData)?(Object.keys(t.overrideTestData).forEach(i=>this.overrideSingleTest(i,t.overrideTestData[i])),delete t.overrideTestData):ou.error("invalid overrideTestData",{overrideTestData:t.overrideTestData,projectId:r})),this.isObjectNotArray(t)&&t.overrideAllTestsData!==void 0&&(ir.isObject(t.overrideAllTestsData)&&!ir.isEmpty(t.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,t.overrideAllTestsData)),delete t.overrideAllTestsData):ou.error("invalid overrideAllTestsData",{overrideAllTestsData:t.overrideAllTestsData,projectId:r})),this.isArrayOfObjects(t)&&e&&this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,t)),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}ou.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 ir.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(i=>{let n=r.map(d=>this.generateTestUniqId(d)),o=n.indexOf(i),a=n.lastIndexOf(i),c=r[o],l=this.createNewTestItems(c,t);return r.splice(o,a-o+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,i)=>{let n=se();return{...e,resultId:n,testData:{value:r,index:i+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 Mi(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ze.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var nr,Ze,cS,lS,uS,pS,Co,Eg=I(()=>{"use strict";nr=R(require("lodash"));F();ae();ls();gs();ge();X();W();Lt();ki();hg();bs();nu();oe();de();Sg();Ri();Ze=P("test-run-status"),cS=Sr(),lS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,uS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,pS=it();Co=class{constructor(e,t,r,i){this.testInfoList=e;this.options=t;this.branchToUse=i;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.userTestDataParams={};this.seleniumPerfStats=new Pr;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData,this.userTestDataString=this.options.testDataString;let n=ti(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:xn||t.parallel||1,browser:n,gitBranch:cS,gitCommit:lS,gitRepoUrl:uS,runnerVersion:pS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:i,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:i,executionId:n,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:v,allLabels:b}=a,T={originalTestResultId:t,previousTestResultId:r,config:nr.cloneDeep(c),testId:l,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...T,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:v,allLabels:b},lu({projectId:i,runId:n,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:T})}testStart(e,t,r,i){let n=this.getTestResult(r);return n.workerId=e,Z.onTestStarted(n,e,i,r),n}async updateTestStatusRunning(e,t,r){var l;let{project:i,remoteRunId:n,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Po(i,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){Ze.error("failed to upload test data artifact (runner)",{err:d})}let c=nr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,kr(i,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:n,testRetryKey:r})}async testStartReport(e,t,r){var n;if(Qe(e,this.options))return;let i=this.exportsGlobal;try{let o=await Mi(this.options.beforeTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token),a=Array.isArray(this.userTestDataParams)?{}:this.userTestDataParams||{},c=(n=e.config)!=null&&n.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 Ze.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,i,n){let o=this.testStart(e,t,r,i);return this.testStartReport(o,t,n)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Ze.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,i){let{name:n,testId:o,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Xe.EVALUATING&&Dt.isTestStatusEnabled){Z.onTestIgnored(e,r,`test in ${Xe.EVALUATING} status`);return}if(l){Z.onTestPassed(n);return}Z.onTestFailed(r,r.failureReason,Ke(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,i,c)}calcResultText(e){return e.success?fe.PASSED:fe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Z.onTestIgnored(e,r,`test in ${Xe.QUARANTINE}`)}monitorMemoryUsage(e){let t=Yc();t.isOverThreshold&&Ze.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,i,n){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=i,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&&iu(o,Ze),o.resultUrl=Ke(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,n),this.monitorMemoryUsage(o),Z.onTestFinished(o,e,n);let c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,r,i){var o;let n=r.exportsGlobal;try{try{await Mi(this.options.afterTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token)}catch(a){Ze.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 kr(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,...i},5)}catch(a){throw Ze.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,i,n,o){let a=this.testEnd(e,t,r,i,n);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let i="",{APP_FROM_DEVICE:n,VIRTUAL_BUILD:o}=Gc;return e&&(i=n),Zr(t,r)&&(i=o),i}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,i=(o=e.gridData)==null?void 0:o.type,n=t.map(a=>{var f,h,g,y;let c=e.browser?ii(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=es(O,i)&&si(a.nativeApp)&&!e.appId,d=Zt(e)&&(Zr(a.nativeApp,i)||l),m=Qe(a,e)||d,u={testId:a.testId,testOptimization:a.testOptimization,status:m?fe.SKIPPED:fe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Xe.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,i)},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(n)}async endKeepAlive(e,t,r){e==="redis"&&await Ci.end(r,t),e==="mongo"&&await wi.end(t)}async executionStart(e,t,r,i,n){Ze.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;hs(()=>Promise.all([this.endKeepAlive(d,t,l),Ao("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:n}},u=this.userTestDataString,f=await Mi(new Function(u||""));if(f&&(this.userTestDataParams=f,Array.isArray(f))){let E=new Ni(f,nr.cloneDeep(this.testInfoList),t);this.testInfoList=E.overrideTestData(!0)}let h=await Mi(o.beforeSuite,m),g=new Ni(h,nr.cloneDeep(this.testInfoList),t);this.testInfoList=g.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=h;let{testInfoList:y}=this,v=[],b=[],T=[];for(let E of y){if(E.isBeforeTestPlan){v.push(E);continue}if(E.isAfterTestPlan){T.push(E);continue}b.push(E)}let w=async()=>{let E=nr.cloneDeep(this.testRunStatus);await ie(Object.keys(E),async B=>{var j;let V=E[B],S=(j=V.config)==null?void 0:j.testData,A=V.testId,N=await Po(t,A,B,S,c.defaults);N&&(delete V.config.testData,V.config.testDataUrl=N)});let C=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),_=cu({executionId:e,projectId:t,labels:i||[],startTime:r,executions:E,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:C,intersections:o.intersections});return this.executionStartedPromise=_,_.catch(B=>Ze.error(B)),_};try{await w()}catch(E){Ze.error("Failed to start suite",{err:E}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:v,tests:b,afterTests:T}}concatSeleniumPerfMarks(e){nr.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=Qc(this.testRunStatus),r=t.length,i=0,n=0,o=0;for(let{status:m,testStatus:u}of t)m===fe.PASSED&&i++,m===fe.SKIPPED&&n++,m===fe.FAILED&&u===Xe.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await Mi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:i,skipped:n})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ze.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await gg(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Ao("FINISHED",e,this.options.project,r===i+n+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw Ze.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,i){let n=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await au(e,["QUEUED"],t,r,i,this.startTime,null,this.options.project);for(let o of n){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=i}return this.testRunStatus}}});function uu(s){var n;let e=s.canary?"-master.zip":".zip",t=`${Jt}/testim-headless${e}`,r=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(n=s.company)==null?void 0:n.companyId,projectId:s.project,runnerEnvironment:Vs});return r||(dS.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),r=`${Jt}/testim-headless.zip`),!(s.ext||s.extensionPath)&&r&&(t=r,s.testimHeadlessExtensionDownloadUrl=r),{chrome:t,"edge-chromium":t}}function Ig(s){let{chrome:e}=uu(s);return e}function ko(s){let e=`${Jt}/sessionPlayer`;return s.canary?`${e}-master`:e}var dS,Fi=I(()=>{"use strict";oe();de();W();dS=P("runOptionsUtils")});function Ts(s){var i;let t=(i=new RegExp(`^\\b(${Object.values(pu).join("|")})`).exec(s))==null?void 0:i[0];return t||pu[Pd]||"usw2"}var pu,xg,Oo=I(()=>{"use strict";oe();pu={"us-west-2":"usw2","eu-central-1":"euc1"},xg=Object.fromEntries(Object.entries(pu).map(([s,e])=>[e,s]))});function Cg(s,e){if(e){if(!bS.has(e)){Ui.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var Ag,Pg,Gt,kg,Og,_g,_o,Dg,Ui,mS,fS,Bi,gS,hS,yS,ne,bS,Do=I(()=>{"use strict";Ag=R(require("ms")),Pg=R(require("p-retry")),Gt=R(require("node:os")),kg=R(require("portfinder")),Og=R(require("node:child_process"));F();He();ge();_g=R(require("node:fs")),_o=R(require("node:fs/promises")),Dg=require("node:path");X();W();Fi();ae();de();F();Oo();Ui=P("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"},Bi=`${Gt.tmpdir()}/LT`,gS=`${Bi}/LT`,hS=(0,Ag.default)("15m"),yS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===D.TESTIM_LAMBDATEST||e.type===D.LAMBDATEST||e.type===D.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t,r){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=du(t,r),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?hS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(gS))return;let t=fS[Gt.platform()+Gt.arch()];if(!t)throw new Error(`tunnel on ${Gt.platform()+Gt.arch()} platform is not supported.`);let r=`${Bi}.zip`;await Ye(`${mS}/${t}`,r),await ct(r,Bi)}static async chmodLtTunnel(e){if(!(Gt.platform()==="win32"||!await ye(e))){try{await _o.access(e,_g.constants.X_OK);return}catch{}try{await _o.chmod(e,"777")}catch(r){throw Ui.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await pe(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await kg.getPortPromise(),{gridData:r={},gridUsername:i,gridPassword:n,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;ne.tunnelName=se();let l=["--tunnelName",ne.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,...Kc(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(i&&n)l=[...l,"--user",i,"--key",n];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 ne.delay(3e3),await ne.chmodLtTunnel((0,Dg.join)(Bi,"LT")),ne.tunnel=Og.spawn("./LT",l,{cwd:Bi});let d="",m="";ne.tunnel.stdout.on("data",u=>{d+=u.toString()}),ne.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,Pg.default)(()=>we(`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});Ui.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),Ui.error("Failed to start LT tunnel",{err:u}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ne.tunnel))return new Promise((t,r)=>{ne.tunnel.on("close",i=>{i&&r(new Error(`tunnel process exited with code ${i}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,i,n,o,a,c){var E,C;if(!this.isActive)return{};let l=ne.lambdatestConfig.CAPABILITIES[t]||{},d={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:Cg(i,a==null?void 0:a.os)||Cg(i,(E=o==null?void 0:o.lt)==null?void 0:E.platform)||l.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??yS,version:t==="safari"&&((C=o==null?void 0:o.lt)==null?void 0:C.safari_version)||l.version};if(c!==K.APPIUM&&c!==K.SELENIUM&&!f){let _=uu({canary:u});!h&&_[t]&&(m=[...m,_[t]]),h&&Me(h)&&(m=[...m,h]),m.length||Ui.warn("No extension was loaded in LambdaTestService",{extUrls:_,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&Me(g)&&(m=[...m,g]);let v=Ts(e.project||""),T={euc1:"eu"}[v],w=T?{region:T}:{};return{build:r,name:`${i} - ${n}`,...w,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.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()}}},bS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey","macOS Catalina","macOS Big Sur"])});var Lg,TS,Lo,mu=I(()=>{"use strict";X();Lg=["platformName","platform","app","bundleId","appPackage","extensions"],TS=["selenium_version","protocol","host","port","path","build"],Lo=(s,e)=>{let t=e==="lambdaTest"?[...Lg,...TS]:Lg,r=[],i=[s];for(;i.length;){let n=i.pop();for(let[o,a]of Object.entries(n))t.includes(o)&&r.push(o),a&&typeof a=="object"&&i.push(a)}if(r.length)throw new x(`Custom capabilities contains forbidden keys: ${r.join(", ")}`)}});function vS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Wg(s){return Ug.readFileSync(s,{encoding:"base64"})}function Vg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&Me(s))&&s){let r=Wg(s);vs.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${hu(r)} current extension count: ${e.length}`),e.push(r)}}function Gg(s,e,t,r,i){if(i!=null&&i.isLambdatestRun())return;let n=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!n){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;vs.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&n&&(a=No.basename(n));let c=No.join(process.cwd(),a),l=Wg(c);vs.info(`adding extension: testim zipped, path: ${c} length: ${l.length} hash: ${hu(l)} current extension count: ${e.length}`),e.push(l)}function SS(s,e,t,r,i,n,o,a){var g,y;let c=t.seleniumName||t.browserValue,l=[],d=[...$g];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":fu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":fu.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(gu(i)){let v=O.flags.DFAcceptInsecureOrigins.getValue();typeof v=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${v}`),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}gu(i)&&c==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(v=>d.push(`--${v}`));try{let v=Mo();v.length&&v.forEach(b=>d.push(`--disable-features=${b}`))}catch{}e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=fu.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+Wc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),Vg(r,l,o),a===K.EXTENSION&&Gg(e,l,d,n,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 ne.isLambdatestGrid(i)&&delete m.w3c,e.oldCapabilities&&i.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||i.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function IS(s,e,t){let r={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Mg.join(","),"browser.helperApps.neverAsk.openFile":Mg.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 ws(s){return`${s.width}x${s.height}`}function kS(s){let{platform:e}=s;if(!e)return ws(Fg);let t=e.split(" ")[1];return e.startsWith("Windows")&&PS.has(t)?ws(xS):e==="Linux"?ws(RS):e.startsWith("macOS")?ws(CS):ws(e==="OS X El Capitan"||e==="OS X Yosemite"?AS:Fg)}function OS(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let i={"sauce:options":{name:e}};if(i["sauce:options"].screenResolution=kS(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 n=(0,jg.cloneDeep)(t.sl);return delete n.screenResolution,t.browserValue!=="safari"&&delete n.safari_version,et.merge(n,i,r)}return et.merge(i,r)}return{}}function _S(s){let{runnerOptions:e}=s;if(et.isEmpty(e.browserstack))return{};let{projectData:t,testRunConfig:r,testId:i,testName:n,executionId:o,executionName:a}=s,c={buildName:`${a} - ${o}`,sessionName:`${n} - ${i}`,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 DS(s){return s.perfecto?s.perfecto:{}}function LS(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 NS(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:i}=s,n=r||t.user||e.user,o=i||t.key||e.key,a={};return n&&o&&(a.Authorization=bc(n,o)),a}function Mo(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function Fo(s){var _,B,V,S;let{overrideConfiguration:e,browserOptions:t,testId:r,testName:i,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:d,testResultId:m,lambdatestService:u,mode:f,customCapabilities:h}=s;if(o.mode==="local"){let A=[],N=[...$g],j={};t.headless&&N.push("--headless"),t.silentDebuggerExtensionApi&&N.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&N.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let H=Mo();H.length&&H.forEach(G=>N.push(`--disable-features=${G}`))}catch{}return t.chromeExtraArgs&&t.chromeExtraArgs.forEach(H=>N.push(`--${H}`)),t.chromeBinaryLocation&&(j.binary=t.chromeBinaryLocation),f!==K.SELENIUM&&Gg(t,A,N,null,u),Vg(a,A,u),{logLevel:Ng,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:N,extensions:A,...j},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:g,driverRequestRetries:y}=t,v=NS(t,o),b={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Ng,connectionRetryTimeout:g,connectionRetryCount:y,getSessionTimeout:Math.max(u.getSessionTimeout,t.getSessionTimeout),getSessionRetries:u.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!et.isEmpty(v)&&{headers:v},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};gu(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 T=Number(t.browserTimeout/1e3),w=t.browser||(n==null?void 0:n.browserValue),E={runnerOptions:t,testId:r,testName:i,testRunConfig:n,executionId:c,executionName:l,projectData:d};et.merge(b.desiredCapabilities,OS(t,i,n),_S(E),DS(t),LS(t,w,T),u==null?void 0:u.getCapabilities(t,w,c,m,i,n,e,f));let C=null;switch(!t.ext&&!t.extensionPath&&((_=o.host)!=null&&_.endsWith(".testim.io"))&&!t.canary&&f===K.EXTENSION&&(w==="chrome"||w==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(C="/opt/testim-headless"),w){case"chrome":case"edge-chromium":b=ES(b,t,n,a,o,C,u,f);break;case"firefox":b=IS(b,t,u);break;case"safari":case"safari technology preview":b=vS(b,w);break;default:break}h?(Lo(h,o.type),et.merge(b.desiredCapabilities,h)):et.merge(b.desiredCapabilities,t.seleniumCapsFileContent);try{let A={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},N=J=>J[o.provider]||J[b.host]||J[A[b.host]],j=J=>{var xe,Te;return N(J)||J[(xe=b.desiredCapabilities)==null?void 0:xe.browserName]||J[(Te=b.desiredCapabilities)==null?void 0:Te.version]||J||{}},H=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),G=j(j(H));Object.keys(G).length&&(vs.info(`Adding custom capabilities: ${JSON.stringify(G)}`),Object.assign(b.desiredCapabilities,G))}catch(A){vs.error("Failed to load custom capabilities",{error:A,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(b.desiredCapabilities&&!b.capabilities&&(wS(b),b.capabilities={alwaysMatch:b.desiredCapabilities,firstMatch:[{}]},delete b.desiredCapabilities),b.hostname=b.host,s.printFinalCaps){let A=(B=b.capabilities)==null?void 0:B.alwaysMatch,N=JSON.parse(JSON.stringify(b)),j=(V=N==null?void 0:N.capabilities)==null?void 0:V.alwaysMatch,H=J=>J.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(J=>{var xe,Te;j!=null&&j[J]&&(j[J].extensions=(Te=(xe=A==null?void 0:A[J])==null?void 0:xe.extensions)==null?void 0:Te.map(H))}),j!=null&&j.loadExtension&&(j.loadExtension=(S=A==null?void 0:A.loadExtension)==null?void 0:S.map(H));let G=require("node:util");console.log(G.inspect(N,{showHidden:!1,depth:null,colors:!0}))}return b}var Ug,No,Bg,et,jg,vs,Ng,fu,$g,hu,gu,wS,ES,Mg,Fg,RS,xS,CS,AS,PS,Uo=I(()=>{"use strict";Ug=R(require("node:fs")),No=R(require("node:path")),Bg=R(require("node:crypto")),et=R(require("lodash"));F();oe();W();de();ae();Do();mu();jg=require("lodash"),vs=P("testim-desired-capabilities-builder"),Ng=Rn?"debug":"silent",fu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},$g=["--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"],hu=(...s)=>Bg.createHash("sha256").update(s.join("")).digest("hex"),gu=s=>s.type===D.DEVICE_FARM||s.type===D.HYBRID&&s.provider==="devicefarm",wS=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 i=JSON.parse(t);if(!Array.isArray(i))return;i.forEach(n=>{delete e[n]})}catch{vs.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};ES=et.memoize(SS,(s,e,t,r,i,n)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(et.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(i.type);return hu(o,a,c,r,l,n)}),Mg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Fg={width:1920,height:1080},RS={width:1920,height:1200},xS={width:2560,height:1600},CS={width:2360,height:1770},AS={width:2048,height:1536},PS=new Set(["7","8","8.1","10","11"])});function Be(s){var e,t,r,i,n,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"||((i=s.message)==null?void 0:i.match(/did not match a known command/))||((n=s.message)==null?void 0:n.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 qg(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 yu=I(()=>{"use strict"});function bu(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 i(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function n(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 n(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=n(u,"stroke-width");return!!g&&parseInt(g,10)>0}return n(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 n(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 bu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(n(s,"visibility")!=="visible")return!1;let d=!!i(s,u=>Number(n(u,"opacity"))===0),m=!!i(s,u=>n(u,"display")==="none");return!(d||m||!o(s)||c(s))}var zg=I(()=>{"use strict"});var Kg,Jg,Ht,MS,FS,Bo,Yg=I(()=>{"use strict";Kg=R(require("promise-queue")),Jg=R(require("webdriverio"));oe();We();F();W();qr();zg();yu();bs();Ht=P("WebDriverApi"),MS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},FS={implicit:0,pageLoad:1,script:2},Bo=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:i}=this,n=t?t.toString().slice(0,2e3):"";throw Ht.warn("error from selenium",{err:e,testResultId:i,testName:r,crashingFunc:n}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Sc!==void 0&&(e=Sc);let t=1/0;this.queue=new Kg.default(e,t)}async addToQueue(e){var r,i;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(n){return this.rejectWithLog(n,e)}finally{(i=this.seleniumPerfStats)==null||i.markEnd(t)}}async initClient(e,t,r){var o,a,c,l,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let i=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(l=(c=e.capabilities.alwaysMatch)==null?void 0:c["goog:chromeOptions"])==null?void 0:l.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),n=(u=this.seleniumPerfStats)==null?void 0:u.markStart(Oe.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t,extUrl:i}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await Jg.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(n,Oe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",i="N/A",n;try{n=await this.client.status();for(let a of n.nodes||[])for(let c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){r=a,i=c;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.info("grid status",{gridStatusMsg:n.message,ready:n.ready,browserNode:r,gridSlot:i,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 i=a=>{throw Object.assign(a,{executedScript:e}),a},n=()=>this.client.execute(e,t).catch(i),o=()=>this.client.executeScript(e,t).catch(i);if(this.unsupportedActions.has("execute"))return n();t=t.map(a=>{if(a===null){Ht.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(Be(a))return this.unsupportedActions.add("execute"),n();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 i=()=>this.client.executeAsync(e,...t),n=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return i();try{return await n()}catch(o){if(Be(o))return this.unsupportedActions.add("executeAsync"),i();throw o}})}}async executeCDP(e,t={}){var i;if(!this.isChromium())return;let r=await((i=this.client)==null?void 0:i.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 n;return(n=this.client)==null?void 0:n.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(i=>({value:i})),r=()=>this.execute(bu,{ELEMENT:e,[Kt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(i){if(Be(i))return this.unsupportedActions.add("elementIdDisplayed"),r();throw i}})}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(qg(e,this.isSafari(),Ht))})}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 n=[];return n[FS[e]]=t,this.client.setTimeouts(...n)},i=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return i();try{return await r()}catch(n){if(Be(n))return this.unsupportedActions.add("timeouts"),i();throw n}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(i,n){window.scrollTo(i,n)};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(MS);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 n;return(n=this.client)==null?void 0:n.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 n;let t=await((n=this.client)==null?void 0:n.$(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 n;return(n=this.client)==null?void 0:n.$(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 i;return(i=this.client)==null?void 0:i.$(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 i={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(i,"yoffset")&&(i.yOffset=1),this.isSafari()&&!Object.hasOwn(i,"xoffset")&&(i.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let n=await this.client.$(e);await this.client.action("pointer").move({origin:n}).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(),i=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let n=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(n,o),i=async()=>await this.client._setWindowSize(n,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await i()}catch(n){if(Be(n))return this.unsupportedActions.add("windowHandleSize"),r();throw n}})}}setCookie(e,t,r,i,n,o,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:i,secure:n,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){Ht.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 Ht.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 or={};z(or,{getSessionPlayer:()=>ee,options:()=>wu});var jo,wu,Tu,ee,ve=I(()=>{"use strict";jo=require("path");W();wu={playerPath:void 0},ee=()=>{if(Tu)return Tu;let s=(We(),ze($e));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(di(),ze(pi)),t=e(),r=wu.playerPath?(0,jo.resolve)(wu.playerPath,"src/background/sessionPlayerInit.ts"):(0,jo.join)(t,"sessionPlayer.js"),i=require(r);return s.log("getSessionPlayerRequire end"),Tu=i,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&i.setLoggerFormatter&&i.setLoggerFormatter(em),i}});var Xg={};z(Xg,{doubleClick:()=>US});var US,Qg=I(()=>{"use strict";US=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let i=s.events,n={status:"done",success:!0};window.__unloadNavigator=function(){e(n)};let o=function(u){function f(b,T,w){return w>b&&w<T}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,v=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:v}},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{i.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(n)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var ji={};z(ji,{dispatchFocus:()=>BS});function BS(s,e){function t(n){let o=document.createEvent("HTMLEvents");return o.initEvent(n,!0,!1),o}function r(){var o;let n=document.activeElement;for(;(o=n.shadowRoot)!=null&&o.activeElement;)n=n.shadowRoot.activeElement;return n}function i(n,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),n.dispatchEvent(t("focusin")),n.dispatchEvent(t("focus")),typeof n.focus=="function"&&n.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let n=getLocatedElement(s);if(n&&n!==e)try{i(n,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var $i=I(()=>{"use strict"});var sh={};z(sh,{WebDriver:()=>Dr});async function VS(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 $S(r):void 0}catch(r){je.info("Error getting cdpAddress",r);return}}var Ss,th,rh,je,ar,jS,Zg,$S,Or,WS,eh,_r,Dr,Wi=I(()=>{"use strict";Ss=R(require("lodash"));F();We();Uo();th=R(require("p-retry")),rh=R(require("ua-parser-js"));qr();W();yu();Yg();X();de();bs();je=P("webdriver"),[ar,jS]=[0,2],{extractElementId:Zg,getCdpAddressForHost:$S}=Q,Or=()=>(ve(),ze(or)).getSessionPlayer().codeSnippets,WS=()=>(ve(),ze(or)).getSessionPlayer().locatorBuilderUtils,eh=()=>(ve(),ze(or)).getSessionPlayer().utils,_r=()=>(ve(),ze(or)).getSessionPlayer().positionUtils;Dr=class extends Bo{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,V,S,A,N,j,H;let{projectData:r,overrideConfiguration:i,browserOptions:n,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:u,testResultId:f,seleniumPerfStats:h,fastInit:g,lambdatestService:y,printFinalCaps:v,mode:b,customCapabilities:T}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((V=(B=(_=n==null?void 0:n.company)==null?void 0:_.activePlan)==null?void 0:B.premiumFeatures)==null?void 0:V.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let w=Fo({projectData:r,browserOptions:n,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:u,testResultId:f,lambdatestService:y,overrideConfiguration:i,printFinalCaps:v,mode:b,customCapabilities:T});w.desiredCapabilities&&delete w.desiredCapabilities.marionette,w.capabilities&&delete w.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(y==null?void 0:y.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=h;let E=g?0:1500,C=g?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let G=await this.initClient(w,a,f);M("after initResult before getCdpAddress in init"),this.cdpUrl=await VS(G),M("after getCdpAddress in webdriver.js init"),je.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await pe(E),O.flags.dontFocusOnInit.isEnabled()||await C(),M("after focus and delay in webdriver.js init")}catch(G){let J=JSON.stringify(Ss.omit(w,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));je.error("failed to init webdriver",{err:G,capabilitiesAsString:J});let xe=((A=(S=n==null?void 0:n.company)==null?void 0:S.activePlan)==null?void 0:A.plan)==="free";throw(N=G.stack)!=null&&N.includes("at startWebDriverSession")&&((j=G.message)!=null&&j.startsWith("Failed to create session"))&&((H=G.message)!=null&&H.includes("Timeout awaiting 'request'"))&&xe?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(G.message)?new Kr(G.message):/capabilit(y|ies)/.test(G.message)?new kn(G.message):/403 Forbidden/.test(G.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(G.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${G.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=n=>Ss.zip(n.slice(0,-1),n.slice(1)),r=this._keepAliveRequests.map(({start:n})=>n).filter(Boolean),i=t(r).map(([n,o])=>o-n);return Math.max(...i)}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(i=>t.message.includes(i))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),i=(a,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function n(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=se();r(o);try{await this.executeJS(n),this._isAlive=!0,i("end",o),this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0}catch(a){if(i("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,je.warn("close unexpected alert open"),await this.alertAccept().catch(c=>je.warn("failed to click on alert",{err:c}));return}if(je.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;je.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(i=>{try{i(r)}catch{}})}async switchToLocatedFrame(t){let r=await this.getElement(t),i=Zg(r.value);return await this.switchToFrame({ELEMENT:i,[Kt]:i}),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 On:r}}async getElement(t){var n;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(((n=t==null?void 0:t.shadowPath)==null?void 0:n.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
19
- var fn = ${Or().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)`)),i.fail(a),o}}async function cv(){let s=`${Jt}/sessionPlayer_LATEST_RELEASE`;return(await $t(s)).body.toString("utf8")}async function lv(s,e){if(!Me(s)||Me(s)&&e||Ve)return s;let t=await cv();return`${s}-${t}`}function ll(){let s=yt();return ns.resolve(s,"testim-bin")}function uv(){let s=ll();return ns.resolve(s,"sessionPlayer.zip")}async function lf(s,e,t=!1){try{return await Dn(s,e),await ct(e,ll())}catch(r){if(t)throw r;return await lf(s,e,!0)}}async function Ir(s,e){Zn.info("prepare player",{location:s,canary:e});let t=uv();return Ot(async()=>{let r=await lv(s,e);return await lf(r,t),{}},"preparePlayer",cf,[s,e,t])()}var nf,of,ns,af,Zn,cf,ol,sf,pi=I(()=>{"use strict";nf=R(require("ms")),of=R(require("node:fs")),ns=R(require("node:path"));ae();er();af=require("serialize-error");W();Qc();Y();F();Zn=P("prepare runner and testim start"),cf=(0,nf.default)("0.5 day"),ol=16,sf=`The size of the custom extension is more than ${ol}MB`});function pv(){let s=di.type().toLowerCase();return s==="darwin"?di.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?di.arch()==="x64"?"win64":"win32":"linux"}async function to(){let s=pv(),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(mi,10)>591479?"chrome-win":"chrome-win32",i={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},n={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]}/${mi}/${i[s]}.zip`,a=eo.join(ul,i[s]),c=`${a}.zip`,l=eo.join(a,n[s]);if(await ye(l))return l;if(!await ye(c)){let m=(0,pl.default)("Downloading Chromium").start();try{await uf.promises.mkdir(ul),await Xe(o,c)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,pl.default)("Extracting Chromium").start();try{await ct(c,ul)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),l}var uf,di,eo,pl,mi,ul,dl=I(()=>{"use strict";uf=R(require("fs")),di=R(require("os")),eo=R(require("path")),pl=R(require("ora"));Y();F();mi="1000968",ul=eo.join(Vt,`chrome-${mi}`)});async function mf(s,e){return Rr=s,hl=e,await ml()}function ff(s,e){Rr=e.projectId,hl=e.token,fi=e.userAccessKey,lt=s.token,hi=yl(lt),yi=s.refreshToken,fl=s.ngrokToken,gl=s.isNgrokWhitelisted,pf=e.publicIp,df=e.initializedFromCache}function mv(s=Rr,e=hl){return Ot(()=>(gi.info("request to get cli token from server"),Ge({url:`${he()}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",dv*10,{projectId:s,token:e})()}async function fv(){gi.info("request to refresh JWT cli token from server");let s=await Ge({url:`${he()}/auth/refreshToken`,body:{token:lt,refreshToken:yi}});return lt=s.token,hi=yl(lt),s.refreshToken&&(yi=s.refreshToken),lt}async function ml(){try{let s=await mv();return gi.info("successfully get cli token from server"),lt=s.token,hi=yl(lt),yi=s.refreshToken,fl=s.ngrokToken,gl=s.isNgrokWhitelisted,lt}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."):(gi.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Rr}),new x(`While trying to retrieve CLI token, caught error: ${s}`))}}function yl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function _t(){if(!hi)return ml();let s=O.flags.accessTokenExpiryMargin.getValue();if(hi<Date.now()+4*s)try{return await fv()}catch(e){return gi.error("failed to refresh token, executing fallback",e),ml()}return lt}function ro(){return yi}function xr(){return lt?{uid:require("jsonwebtoken").decode(lt).id,ngrokToken:fl,isNgrokWhitelisted:gl}:{}}async function so(){if(!fi||!Rr)return;if(await bl({userAccessKey:fi,projectId:Rr}))return fi;let e=`user access key "${fi}" is invalid for project "${Rr}"`;throw new x(e)}function io(){return pf}function no(){return df}var gi,lt,hi,yi,fl,gl,Rr,hl,fi,pf,df,dv,ut=I(()=>{"use strict";ae();He();er();Y();W();ge();de();gi=P("testim-custom-token"),Rr=null,hl=null,dv=5*60*1e3});function gv(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=gf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function hv(s){let e=gf.exec(s);return e==null?void 0:e[3]}function ao(s){var w,E,A,_,B,V,S,C,D,j,H;let e=s&&hv(s.host),t=s.port,r=s.path,i=s&&gv(s),n=s.token,o=s.slotId,a=(w=s.hybrid)==null?void 0:w.tunnel,c=(E=s.external)==null?void 0:E.user,l=(A=s.external)==null?void 0:A.key,d=s.type,m=d===N.HYBRID?a&&((V=(B=(_=s.hybrid)==null?void 0:_.external)==null?void 0:B[s.hybrid.tunnel])==null?void 0:V.user):c,u=d===N.HYBRID?a&&((D=(C=(S=s.hybrid)==null?void 0:S.external)==null?void 0:C[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,v=(H=s.mobileTokens)==null?void 0:H.iosToken,b=s.apiUrl,T=s.isSupportGrid;return{host:e,port:t,path:r,protocol:i,accessToken:n,slotId:o,gridId:h,tunnel:a,user:c,key:l,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:v,apiUrl:b,isSupportGrid:T}}async function bv(s,e,t,r,i,n){var a;let o;try{o=await n()}catch(c){throw pt.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(bt.UNKNOWN)}if(pt.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw pt.error("invalid response - get grid",{res:o}),new Error(bt.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,Tf(i));let c=ao(o.grid);return yv(t,e,c.gridId,c.slotId,r,c.isSupportGrid),c}throw o.code==="not-found"?new nt(bt.NOT_FOUND):o.code==="no-available-slot"?new Yt(`Failed to run test on ${r} - concurrency limit reached`):(pt.error("invalid code error response - get grid",{res:o}),new nt(bt.UNKNOWN))}function yf(s){return Il(s)}async function bf(s,e,t){let i=(t||await yf(s)).find(n=>n._id===e);if(!i)throw new x(`Failed to find grid id: ${e}`);return ao(i)}async function Tv(s,e,t){let i=(t||await yf(s)).find(n=>(n.name||"").toLowerCase()===e.toLowerCase());if(!i)throw new x(`Failed to find grid name: ${e}`);return ao(i)}async function Tl(s,e){let t=bi[s];if(!t)return;let{slotId:r,gridId:i,browser:n,companyId:o,isSupportGrid:a}=t;if(delete bi[s],!a){if(!r){pt.warn("failed to find grid slot id",{projectId:e});return}pt.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:i,browser:n});try{await vl(o,e,r,i,n)}catch(c){pt.error("failed to release slot",{projectId:e,err:c})}}}async function wv(s){let e=Object.values(bi).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid)try{await wl(s,e)}catch(t){pt.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}function vv(s){hf=global.setInterval(wv,1e4,s)}async function Sv(s){let e=Object.keys(bi);if(e.length){pt.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>Tl(Number(t),s))}catch(t){pt.error("failed to release all slots",{err:t,projectId:s})}}}async function Ev(s){await Sv(s),clearInterval(hf)}function Iv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function Rv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function Tf(s){let t=(()=>oo.isEmpty(s.testobjectSauce)?oo.isEmpty(s.saucelabs)?oo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:i,path:n,protocol:o}=s,a=Iv(t,s),c=Rv(t,s);return{host:r,port:i,path:n,protocol:o,type:t,user:c,key:a,gridId:se()}}async function wf(s,e){let t=s.company.companyId;return await bf(t,e.gridId,s.allGrids)}async function vf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:i,localTmaUrl:n,useChromeLauncher:o,gridId:a,grid:c}=s;if(i||o||n)return{mode:"local"};if(r)return Tf(s);let l=t==null?void 0:t.companyId;if(a)return bf(l,a,e);if(c)return Tv(l,c,e);if(ti(s)||s.tunnelOnlyMode){pt.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new nt("Missing host or grid configuration")}async function Sf(s,e,t,r,i){let{host:n,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 bv(o,h,r,s,t,()=>El({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:n,testResultId:i}))}var oo,pt,bi,gf,hf,yv,Ti,Ef,os=I(()=>{"use strict";oo=R(require("lodash"));ge();W();F();oe();Y();pt=P("grid-service"),bi={},gf=/(^(https?):\/{2})?(.*)/,hf=null;yv=(s,e,t,r,i,n)=>{bi[s]={gridId:t,companyId:e,slotId:r,browser:i,isSupportGrid:n}};Ti={start:vv,end:Ev};Ef=async(s={},e={},t={},r={},i={})=>{var g,y,v;let{company:{companyId:n}={},project:o}=s,{gridId:a,type:c}=e,l=s.browser||t.browserValue,d=Boolean(s.tunnel),{maxRetries:m,currentRetry:u}=i;if(!a||!c||((c===N.TESTIM_LAMBDATEST||c===N.LAMBDATEST)&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e,n,o)),c!==N.HYBRID||!n||!l||!m||!u))return e;let f=await Sl({companyId:n,gridId:a,maxRetries:m,currentRetry:u,browser:l,usingTunnel:d});pt.info("handling hybrid grid",{response:f,companyId:n});let h=ao({...e,...f.connectionDetails,provider:f.provider});return f.provider!=="lambdatest"&&((y=r.disable)==null||y.call(r)),f.provider==="lambdatest"&&await((v=r.enableIfNeeded)==null?void 0:v.call(r,h,n,o)),h}});function vi(){return co||"master"}function If(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){co="master";return}if(s!=null&&s.isArchived)throw new x(`Branch ${s.branch} is archived, run aborted.`);if(s){co=s.branch||s;return}co=e?"master":void 0}var co,Rl=I(()=>{"use strict";Y()});function Cf(s){Ve||(s!=null&&s.userId||(s={anonymousId:"runnerId"}),Af.identify(s))}function dt(s,e){return as("ci",s,e)}function as(s,e,t){if(Ve)return;let r=s?{userId:s}:{anonymousId:"runnerId"};Af.track(Object.assign(r,{event:e,properties:t}))}var xf,Af,cs=I(()=>{"use strict";ae();xf=require("@segment/analytics-node"),Af=new xf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1})});var Pf={};z(Pf,{isCi:()=>ls});var ls,lo=I(()=>{"use strict";ls=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Of(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function _f({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:n,companyName:o,projectName:a,companyPlan:c,source:l,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Of({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:n,companyName:o,projectName:a,companyPlan:c,source:kf(l,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);dt("test-run-ci",y)}function Lf({executionId:s,projectId:e,testId:t,resultId:r,result:i,ucid:n,companyId:o,companyName:a,projectName:c,companyPlan:l,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:v}){try{let b=Of({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:i.wasMockNetworkActivated,source:kf(d,m),isStartUp:h,projectType:g,gridType:v,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(i.success){dt("test-run-ci-success",b);return}dt("test-run-ci-fail",{...b,failureReason:i.failureReason})}catch(b){f.error("failed to update test end analytics",{err:b})}}function Df(s){dt("batch-run-ci",s)}var kf,xl=I(()=>{"use strict";cs();lo();kf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ls&&e?"ci-with-user":ls?"ci":e?"cli-with-user":s});var Al,ue,Mf=I(()=>{"use strict";Al=class{static colorString(e,t){return`${e}${t}${Al.Reset}`}},ue=Al;ue.Reset="\x1B[0m",ue.Bright="\x1B[1m",ue.Dim="\x1B[2m",ue.Underscore="\x1B[4m",ue.Blink="\x1B[5m",ue.Reverse="\x1B[7m",ue.Hidden="\x1B[8m",ue.FgBlack="\x1B[30m",ue.FgRed="\x1B[31m",ue.FgGreen="\x1B[32m",ue.FgYellow="\x1B[33m",ue.FgBlue="\x1B[34m",ue.FgMagenta="\x1B[35m",ue.FgCyan="\x1B[36m",ue.FgWhite="\x1B[37m",ue.FgGray="\x1B[90m",ue.BgBlack="\x1B[40m",ue.BgRed="\x1B[41m",ue.BgGreen="\x1B[42m",ue.BgYellow="\x1B[43m",ue.BgBlue="\x1B[44m",ue.BgMagenta="\x1B[45m",ue.BgCyan="\x1B[46m",ue.BgWhite="\x1B[47m",ue.BgGray="\x1B[100m"});var Ei,Cl,xv,Pl,Av,uo,po,mo,fo,go,ho=I(()=>{"use strict";F();oe();Ei=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===fe.FAILED},Cl=s=>{let{status:e}=s;return e===fe.ABORTED},xv=s=>{let{status:e}=s;return e===fe.PASSED},Pl=s=>s.runnerStatus===Fc.SKIPPED,Av=s=>s.testStatus===Ye.EVALUATING,uo=(s,e)=>Object.values(s).filter(t=>{var r,i;return Pl(t)&&(Qe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((i=t.mobile)==null?void 0:i.isAppForIosVirtualDevice))}).length,po=s=>Object.values(s).filter(e=>Ei(e)&&Av(e)).length,mo=s=>Object.values(s).filter(Ei),fo=s=>Object.values(s).filter(xv),go=s=>Object.values(s).filter(Cl)});function Pv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var kl,yo,Cv,bo,Ff=I(()=>{"use strict";kl=R(require("lodash"));W();ho();yo=P("debug-reporter"),Cv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],bo=class{constructor(e){this.options=e}onTestStarted(e,t){yo.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},i=r.provider,n=r.host,o=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;yo.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:i,host:n,failedGetBrowserAttempts:c,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...kl.default.omit(this.options,Cv),company:kl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,i,n,o,a){let c=Pv(process.argv);yo.info("Test Plan Started",{executionId:n,testPlanName:i,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,i,n){let o=fo(e).length,a=Object.keys(e).length-o;yo.info("Test Plan Finished",{executionId:i,testPlanName:t,isAnonymous:n,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Ol,Lt,Ii=I(()=>{"use strict";oe();Ol=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}},Lt=new Ol});var Ll={};z(Ll,{Reporter:()=>kv});var sr,Ri,Ar,To,Uf,_l,kv,Dl=I(()=>{"use strict";sr=R(require("chalk")),Ri=R(require("lodash"));F();oe();Ii();ho();Ar={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:To}=Wt,Uf="device",_l=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})`,i=`url: ${sr.default.underline(Ke(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${i}`.trim())}onTestFinished(e,t){let r=e.success?fe.PASSED:fe.FAILED,i=`(${e.testId})`,n=Ar[e.success?"success":"error"];console.log(n(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${i} duration: ${Fn(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let i=Ke(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${i}`});console.log(Ar.error("Failed runs are:")),console.log(Ar.error(t.join(`
18
+ \r`)))}onTestPlanFinished(e,t,r,i,n){let o=mo(e),a=fo(e),c=go(e),l=a.length,d=c.length,m=o.length,u="",f="";if(Lt.isTestStatusEnabled){let b=po(e);u=` FAILED-EVALUATING: ${b}`,m-=b,f=` SKIPPED: ${uo(e,this.options)}`}let h=this.buildTestPlanName(n,t),g,y=Ar[m?"error":"success"],v=`PASSED: ${l} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Fn(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${v} (Execution ID: ${i})`:g=`Test plan${h} completed ${v} (${i})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=Ri.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,i=Ri.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,n=Ri.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Ri.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[n,i,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,i,n,o,a){let c=u=>{u.forEach((f,h)=>{var b;let g=(b=f.testData)!=null&&b.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`,v="";f.testOptimization?v=` [${f.testOptimization.reason}]`:Qe(f,this.options)&&(v="-quarantine"),console.log(" ",h+1,":",`${f.name}${v}`,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,i)} test plan with ${m} (${n})`),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,i=this.options.mode===To.APPIUM?Uf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(i)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let i=r===To.APPIUM?Uf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${i} to run ${sr.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 i=this.options.grid||this.options.gridId,n=this.options.mode===To.APPIUM?"device":"browser";if(i)console.log(Ar.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${n} from the grid ${i}`));else if(this.options.useLocalChromeDriver)console.log(Ar.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===To.APPIUM?"Appium":"Selenium";console.log(Ar.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},kv=_l});var Fl={};z(Fl,{Reporter:()=>Mv});function Ov(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function _v(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 Lv(s){return`${s.visitedUrlsJson||""}`}async function Dv(s,e,t,r,i,n){function o(u){let f=Ke(s,t,u.testId,u.resultId,r),h={$:{name:Ov(u),classname:i,time:Hc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(Ei(u)||Cl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=Ei(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Pl(u)&&Qe(u,n)&&Lt.isTestStatusEnabled&&(h.skipped={}),n.urls&&(h["visited-urls-list"]=_v(u),h["visited-urls-json"]=Lv(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},b={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(y),failures:d(y),timestamp:c(e)};if(Lt.isTestStatusEnabled){b.skipped=uo(y,n);let T=po(y);b.failures-=T,b["failure-evaluating"]=T}return{$:b,testcase:Object.keys(y).map(T=>o(y[T]))}}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 mo(u).length+go(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Ml.Builder().buildObject(m)}catch(u){return Nv(u)}}function Nv(s){let e=new Ml.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 Ml,Bf,Nl,Mv,Ul=I(()=>{"use strict";Ml=R(require("xml2js"));F();Bf=require("fs");Ii();ho();Nl=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,i=await Dv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Bf.promises.writeFile(t,i),console.log("JUnit XML file saved to",t),e}catch(n){return console.error("could not save report file",t,n),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};Mv=Nl});var jf={};z(jf,{Reporter:()=>Fv});function us(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 Bl,jl,Fv,$f=I(()=>{"use strict";W();Bl=P("team-city-reporter");jl=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",i=`${e.name} (${e.testId})${r}`;return us(i)}onTestStarted(e,t,r,i){if(r){Bl.debug("skip report test started because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testStarted name='${n}' captureStandardOutput='true' flowId='${i}']`)}onTestFailed(e,t,r,i,n,o){if(n){Bl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${us(t)}' details='${us(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Bl.debug("skip report test finished because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testFinished name='${i}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let i=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${i}' message='${us(r)}']`)}onTestPlanStarted(e,t,r,i){console.log(`##teamcity[testSuiteStarted name='${us(i)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${us(t)}']`)}},Fv=jl});var Wf={};z(Wf,{Reporter:()=>Uv});var $l,Uv,Vf=I(()=>{"use strict";$l=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,i,n){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:n}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},Uv=$l});function vo(s){let{platform:e}=process;e==="win32"?(0,wo.exec)(`start chrome ${s}`):e==="darwin"?(0,wo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,wo.exec)(`google-chrome ${s}`)}var wo,Wl=I(()=>{"use strict";wo=require("child_process")});var Gf={};z(Gf,{Reporter:()=>Bv});var Vl,Bv,Hf=I(()=>{"use strict";F();Wl();Vl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=Ke(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return vo(t)}},Bv=Vl});var Gl,Z,Dt=I(()=>{"use strict";Ff();Gl=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 bo(e)),r===void 0||r.length===0){let{Reporter:i}=await Promise.resolve().then(()=>(Dl(),Ll));if(this.reporters.push(new i(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:n}=await Promise.resolve().then(()=>(Ul(),Fl));this.reporters.push(new n(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>($f(),jf)),r.includes("console")&&Promise.resolve().then(()=>(Dl(),Ll)),r.includes("junit")&&Promise.resolve().then(()=>(Ul(),Fl)),r.includes("json")&&Promise.resolve().then(()=>(Vf(),Wf)),r.includes("chrome")&&Promise.resolve().then(()=>(Hf(),Gf))])).forEach(n=>{n&&this.reporters.push(new n.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,i,n){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,i,n]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var n;let i=t==null?void 0:t(...r);for(let o of this.reporters)await((n=o[e])==null?void 0:n.call(o,...i||r))}}},Z=new Gl});async function Hl(s,e,t){let r=ps[s];if(!r)return;let{slotId:i}=r;if(delete ps[s],!i){Tt.warn("failed to find slot slot id",{companyId:e,workerId:s});return}Tt.info("release slot id",{companyId:e,slotId:i});try{await zl(e,t,i)}catch(n){Tt.error("failed to release slot",{companyId:e,err:n})}}async function jv(s,e){let t=Object.values(ps).filter(Boolean);if(t.length!==0)try{await Jl(s,e,t)}catch(r){Tt.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}function $v(s,e){qf=global.setInterval(()=>jv(s,e),1e4)}async function Wv(s,e){let t=Object.keys(ps);if(t.length){Tt.warn("not all slots released before end runner flow",{companyId:s});try{await ie(t,r=>Hl(Number(r),s,e))}catch(r){Tt.error("failed to release all slots",{err:r,companyId:s})}}}async function Vv(s,e){await Wv(s,e),clearInterval(qf)}async function Kf(s,e,t){let r;try{r=await ql(s,e)}catch(i){throw Tt.error("failed to get slot",{companyId:s,err:i}),new Error(bt.UNKNOWN)}if(Tt.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw Tt.error("invalid response - get slot",{res:r}),new Error(bt.UNKNOWN);if(r.status==="success")return zf(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new nt(bt.NOT_FOUND):r.code==="no-available-slot"?new Yt("Failed to run test - concurrency limit reached"):(Tt.error("invalid code error response - get slot",{res:r}),new nt(bt.UNKNOWN))}async function Jf(s,e,t,r){let i=ps[r];if(!i)throw new Error("slot not found");Object.assign(i,t),zf(r,i),await Kl(s,e,i),Tt.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var Tt,ps,qf,zf,xi,ds=I(()=>{"use strict";ge();W();F();oe();Y();Tt=P("slot-service"),ps={},qf=null,zf=(s,e)=>{ps[s]=e};xi={start:$v,end:Vv}});function Yf(s,e=process){async function t(r){await le(ie(Xf,async i=>i()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Ci.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 i;if(Ci.fatal("Caught unhandled promise rejection",r),!((i=r==null?void 0:r.message)!=null&&i.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Ci.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",i=new Error(r);throw Ci.error(r),t(i),i}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",i=new Error(r);throw Ci.error(r),t(i),i}),e.once("exit",r=>{s(r)})}function ms(s){Xf.push(s)}var Ci,Xf,Pi=I(()=>{"use strict";W();F();Ci=P("process-handler"),Xf=[]});var tg={};z(tg,{installAllLazyDependencies:()=>zv,lazyRequire:()=>mt});async function mt(s,e={}){let t=el(s);if(t)return t;let r;e.silent||(r=(0,Qf.default)(`Installing ${s} before first usage...`).start());try{let i=await qv(s);return r&&r.succeed(),i}catch(i){Hv.warn("failed to install dependency lazily",{dependency:s,err:i});let n=eg(s),o=`${s}@${n}`,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),i}}async function qv(s){return fs.has(s)||(fs.set(s,Zf(s)),fs.get(s).catch(()=>{fs.delete(s)})),fs.get(s)}async function Zf(s){let e=el(s);if(e)return e;let t=eg(s),r=`${s}@${t}`;return await Yn(yt(),r),tr(s)}async function zv(){let s=Object.keys(bc);for(let e of s)await Zf(e)}function eg(s){let e=Object.entries(bc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Qf,Hv,fs,ki=I(()=>{"use strict";Qf=R(require("ora"));is();W();F();Sn();ai();Hv=P("lazy-require"),fs=new Map});var rg,So,sg=I(()=>{"use strict";rg=require("istanbul-lib-report"),So=class extends rg.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 ig,ng,og,Oi,wt,ag,Eo,Xl,cg,Kv,lg,ug,Jv,Xv,pg,Yv,Qv,Zv,eS,tS,dg,mg=I(()=>{"use strict";ig=R(require("ora")),ng=R(require("dayjs")),og=R(require("test-exclude")),Oi=R(require("fs")),wt=R(require("path")),ag=R(require("istanbul-reports")),Eo=R(require("istanbul-lib-report"));ge();Y();F();W();ki();sg();Xl=P("test-run-status"),cg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Kv=s=>!!cg(s).search,lg=s=>s?cg(s).pathname.substring(1):"",ug=(s,e)=>{let t=lg(e);return!new og.default({relativePath:!1,include:s}).shouldInstrument(t)},Jv=s=>s.substring(0,s.indexOf("?")),Xv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await mt("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)},pg=(s,e)=>`${wt.resolve(s,lg(e))}.js`,Yv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async i=>{if(!i)return;let n=i.toObject();await ie(n.sources,async(o,a)=>{if(ug(r,o))return;let c=pg(e,o);await Oi.promises.mkdir(wt.parse(c).dir,{recursive:!0}),await Oi.promises.writeFile(c,n.sourcesContent[a])})})},Qv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Kv(e)&&(e=Jv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=wt.dirname(this.getPath(s));return wt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Zv=async(s,e,t,r)=>{let{codeCoverageReporter:i}=s,n={},o=Eo.createContext({dir:t,coverageMap:e,watermarks:Eo.getDefaultWatermarks(),sourceFinder:a=>{try{let c=pg(r,a);return Oi.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new So({appendToObject:n}).execute(o),Array.isArray(i)&&i.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Qv}),ag.create(a,c).execute(o)}),n},eS=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:i}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await mt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>ug(i,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},tS=async(s,e)=>{let{mergeProcessCovs:r}=await mt("@bcoe/v8-coverage"),i={result:[]},n=new Map,a=(await Ql(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await _i(c,9e4);await ie(l,async d=>{if(!n.has(d.url)){let m=d.text;d.sourceUrl&&(n.set(d.url,"TEMP"),m=await Yl(d.sourceUrl)),n.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,i=r([i,{result:[d]}])})},{concurrency:20}),{covUrlMap:n,mergedCoverages:i}},dg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Xl.info("start js coverage process");let i=(0,ig.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),n=wt.resolve(s.codeCoverageReportPath||"./coverage"),o=wt.resolve(n,`.js/${(0,ng.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?wt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([mt("istanbul-lib-coverage"),tS(s.project,r)]);if(l.result.length===0){i.fail("Failed to report coverage information - js code coverage is empty");return}Xl.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),u={};await ie(l.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:v}=d.get(h),b=await Xv({sourceMapType:v,source:y,sourceMapDir:a});u[h]=b;let T=await eS(s,{source:y,sourceMap:b,functions:g});m.merge(T)}),await Yv(s,o,u);let f=await Zv(s,m,n,o);return i.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof x?i.fail(`${l}, missing arg: ${c.message}`):i.fail(l),Xl.error(l,{err:c})}}});var fg={};z(fg,{SELENIUM_PERF_MARKS:()=>Oe,SeleniumPerfStats:()=>Cr});var Oe,rS,Cr,gs=I(()=>{"use strict";F();Oe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},rS=["ALL",...Object.values(Oe)],Cr=class{constructor(){this.marks=Object.fromEntries(rS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();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`,$n(r,50)],[`${t}_P95`,$n(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var bg={};z(bg,{initServer:()=>nS,mapFilesToLocalDrive:()=>eu});function eu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Io[t.id]?{screenshot:Io[t.id]}:{})),Object.keys(Ro).forEach(t=>{s.assets||={},s.assets[yg[t]]=Ro[t]}),s.assets||={},s.assets.screenshots=Object.values(Io)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function nS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await mt("multer"),i=typeof t=="string"?t:sS;await Zl.promises.mkdir(i,{recursive:!0});let n=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=Li.join(i,m.testResultId);try{await Zl.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=Li.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,hg.default)();o.disable("x-powered-by"),o.post("/",n.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(Io[d.stepId]=c.file.path),d.testResultId&&iS.includes(d.subType)&&(Ro[d.subType]||=[],Ro[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 Zl,gg,Li,hg,sS,Io,Ro,yg,iS,tu=I(()=>{"use strict";Zl=R(require("fs")),gg=R(require("os")),Li=R(require("path")),hg=R(require("express"));Y();ki();sS=Li.join(gg.tmpdir(),"testim/rca/"),Io={},Ro={},yg={"test-log":"consoleLogs","har-file":"networkLogs"},iS=Object.keys(yg)});var ir,ru,Di,Tg=I(()=>{"use strict";ir=R(require("lodash"));F();W();ru=P("override-test-data-builder"),Di=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return ir.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)&&!ir.isEmpty(t.overrideTestData)?(Object.keys(t.overrideTestData).forEach(i=>this.overrideSingleTest(i,t.overrideTestData[i])),delete t.overrideTestData):ru.error("invalid overrideTestData",{overrideTestData:t.overrideTestData,projectId:r})),this.isObjectNotArray(t)&&t.overrideAllTestsData!==void 0&&(ir.isObject(t.overrideAllTestsData)&&!ir.isEmpty(t.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,t.overrideAllTestsData)),delete t.overrideAllTestsData):ru.error("invalid overrideAllTestsData",{overrideAllTestsData:t.overrideAllTestsData,projectId:r})),this.isArrayOfObjects(t)&&e&&this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,t)),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}ru.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 ir.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(i=>{let n=r.map(d=>this.generateTestUniqId(d)),o=n.indexOf(i),a=n.lastIndexOf(i),c=r[o],l=this.createNewTestItems(c,t);return r.splice(o,a-o+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,i)=>{let n=se();return{...e,resultId:n,testData:{value:r,index:i+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 Ni(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ze.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var nr,Ze,oS,aS,cS,lS,xo,wg=I(()=>{"use strict";nr=R(require("lodash"));F();oe();os();ds();ge();Y();W();Dt();Pi();mg();gs();tu();ae();de();Tg();Ii();Ze=P("test-run-status"),oS=vr(),aS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,cS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,lS=it();xo=class{constructor(e,t,r,i){this.testInfoList=e;this.options=t;this.branchToUse=i;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.userTestDataParams={};this.seleniumPerfStats=new Cr;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData,this.userTestDataString=this.options.testDataString;let n=ei(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:Rn||t.parallel||1,browser:n,gitBranch:oS,gitCommit:aS,gitRepoUrl:cS,runnerVersion:lS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:i,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:i,executionId:n,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:v,allLabels:b}=a,T={originalTestResultId:t,previousTestResultId:r,config:nr.cloneDeep(c),testId:l,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...T,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:v,allLabels:b},nu({projectId:i,runId:n,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:T})}testStart(e,t,r,i){let n=this.getTestResult(r);return n.workerId=e,Z.onTestStarted(n,e,i,r),n}async updateTestStatusRunning(e,t,r){var l;let{project:i,remoteRunId:n,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Co(i,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){Ze.error("failed to upload test data artifact (runner)",{err:d})}let c=nr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,Pr(i,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:n,testRetryKey:r})}async testStartReport(e,t,r){var n;if(Qe(e,this.options))return;let i=this.exportsGlobal;try{let o=await Ni(this.options.beforeTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token),a=Array.isArray(this.userTestDataParams)?{}:this.userTestDataParams||{},c=(n=e.config)!=null&&n.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 Ze.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,i,n){let o=this.testStart(e,t,r,i);return this.testStartReport(o,t,n)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Ze.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,i){let{name:n,testId:o,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Ye.EVALUATING&&Lt.isTestStatusEnabled){Z.onTestIgnored(e,r,`test in ${Ye.EVALUATING} status`);return}if(l){Z.onTestPassed(n);return}Z.onTestFailed(r,r.failureReason,Ke(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,i,c)}calcResultText(e){return e.success?fe.PASSED:fe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Z.onTestIgnored(e,r,`test in ${Ye.QUARANTINE}`)}monitorMemoryUsage(e){let t=qc();t.isOverThreshold&&Ze.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,i,n){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=i,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&&eu(o,Ze),o.resultUrl=Ke(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,n),this.monitorMemoryUsage(o),Z.onTestFinished(o,e,n);let c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,r,i){var o;let n=r.exportsGlobal;try{try{await Ni(this.options.afterTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token)}catch(a){Ze.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 Pr(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,...i},5)}catch(a){throw Ze.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,i,n,o){let a=this.testEnd(e,t,r,i,n);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let i="",{APP_FROM_DEVICE:n,VIRTUAL_BUILD:o}=jc;return e&&(i=n),Xr(t,r)&&(i=o),i}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,i=(o=e.gridData)==null?void 0:o.type,n=t.map(a=>{var f,h,g,y;let c=e.browser?si(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=Yr(O,i)&&ri(a.nativeApp)&&!e.appId,d=Zt(e)&&(Xr(a.nativeApp,i)||l),m=Qe(a,e)||d,u={testId:a.testId,testOptimization:a.testOptimization,status:m?fe.SKIPPED:fe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ye.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,i)},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(n)}async endKeepAlive(e,t,r){e==="redis"&&await xi.end(r,t),e==="mongo"&&await Ti.end(t)}async executionStart(e,t,r,i,n){Ze.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;ms(()=>Promise.all([this.endKeepAlive(d,t,l),Ao("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:n}},u=this.userTestDataString,f=await Ni(new Function(u||""));if(f&&(this.userTestDataParams=f,Array.isArray(f))){let E=new Di(f,nr.cloneDeep(this.testInfoList),t);this.testInfoList=E.overrideTestData(!0)}let h=await Ni(o.beforeSuite,m),g=new Di(h,nr.cloneDeep(this.testInfoList),t);this.testInfoList=g.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=h;let{testInfoList:y}=this,v=[],b=[],T=[];for(let E of y){if(E.isBeforeTestPlan){v.push(E);continue}if(E.isAfterTestPlan){T.push(E);continue}b.push(E)}let w=async()=>{let E=nr.cloneDeep(this.testRunStatus);await ie(Object.keys(E),async B=>{var j;let V=E[B],S=(j=V.config)==null?void 0:j.testData,C=V.testId,D=await Co(t,C,B,S,c.defaults);D&&(delete V.config.testData,V.config.testDataUrl=D)});let A=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),_=iu({executionId:e,projectId:t,labels:i||[],startTime:r,executions:E,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:A,intersections:o.intersections});return this.executionStartedPromise=_,_.catch(B=>Ze.error(B)),_};try{await w()}catch(E){Ze.error("Failed to start suite",{err:E}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:v,tests:b,afterTests:T}}concatSeleniumPerfMarks(e){nr.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=Kc(this.testRunStatus),r=t.length,i=0,n=0,o=0;for(let{status:m,testStatus:u}of t)m===fe.PASSED&&i++,m===fe.SKIPPED&&n++,m===fe.FAILED&&u===Ye.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await Ni(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:i,skipped:n})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ze.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await dg(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Ao("FINISHED",e,this.options.project,r===i+n+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw Ze.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,i){let n=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await su(e,["QUEUED"],t,r,i,this.startTime,null,this.options.project);for(let o of n){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=i}return this.testRunStatus}}});function ou(s){var n;let e=s.canary?"-master.zip":".zip",t=`${Jt}/testim-headless${e}`,r=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(n=s.company)==null?void 0:n.companyId,projectId:s.project,runnerEnvironment:Vs});return r||(uS.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),r=`${Jt}/testim-headless.zip`),!(s.ext||s.extensionPath)&&r&&(t=r,s.testimHeadlessExtensionDownloadUrl=r),{chrome:t,"edge-chromium":t}}function vg(s){let{chrome:e}=ou(s);return e}function Po(s){let e=`${Jt}/sessionPlayer`;return s.canary?`${e}-master`:e}var uS,Mi=I(()=>{"use strict";ae();de();W();uS=P("runOptionsUtils")});function hs(s){var i;let t=(i=new RegExp(`^\\b(${Object.values(au).join("|")})`).exec(s))==null?void 0:i[0];return t||au[Ad]||"usw2"}var au,Eg,ko=I(()=>{"use strict";ae();au={"us-west-2":"usw2","eu-central-1":"euc1"},Eg=Object.fromEntries(Object.entries(au).map(([s,e])=>[e,s]))});function Ig(s,e){if(e){if(!hS.has(e)){Fi.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var Rg,xg,Gt,Ag,Cg,Pg,Oo,kg,Fi,pS,dS,Ui,mS,fS,gS,ne,hS,_o=I(()=>{"use strict";Rg=R(require("ms")),xg=R(require("p-retry")),Gt=R(require("node:os")),Ag=R(require("portfinder")),Cg=R(require("node:child_process"));F();He();ge();Pg=R(require("node:fs")),Oo=R(require("node:fs/promises")),kg=require("node:path");Y();W();Mi();oe();de();F();ko();Fi=P("lambdatestService"),pS="https://downloads.lambdatest.com/tunnel/v3",dS={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"},Ui=`${Gt.tmpdir()}/LT`,mS=`${Ui}/LT`,fS=(0,Rg.default)("15m"),gS="2560x1440",ne=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){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=cu(t,r),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?fS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(mS))return;let t=dS[Gt.platform()+Gt.arch()];if(!t)throw new Error(`tunnel on ${Gt.platform()+Gt.arch()} platform is not supported.`);let r=`${Ui}.zip`;await Xe(`${pS}/${t}`,r),await ct(r,Ui)}static async chmodLtTunnel(e){if(!(Gt.platform()==="win32"||!await ye(e))){try{await Oo.access(e,Pg.constants.X_OK);return}catch{}try{await Oo.chmod(e,"777")}catch(r){throw Fi.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await pe(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Ag.getPortPromise(),{gridData:r={},gridUsername:i,gridPassword:n,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;ne.tunnelName=se();let l=["--tunnelName",ne.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,...Gc(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(i&&n)l=[...l,"--user",i,"--key",n];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 ne.delay(3e3),await ne.chmodLtTunnel((0,kg.join)(Ui,"LT")),ne.tunnel=Cg.spawn("./LT",l,{cwd:Ui});let d="",m="";ne.tunnel.stdout.on("data",u=>{d+=u.toString()}),ne.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,xg.default)(()=>we(`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});Fi.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),Fi.error("Failed to start LT tunnel",{err:u}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ne.tunnel))return new Promise((t,r)=>{ne.tunnel.on("close",i=>{i&&r(new Error(`tunnel process exited with code ${i}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,i,n,o,a,c){var E,A;if(!this.isActive)return{};let l=ne.lambdatestConfig.CAPABILITIES[t]||{},d={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:Ig(i,a==null?void 0:a.os)||Ig(i,(E=o==null?void 0:o.lt)==null?void 0:E.platform)||l.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??gS,version:t==="safari"&&((A=o==null?void 0:o.lt)==null?void 0:A.safari_version)||l.version};if(c!==K.APPIUM&&c!==K.SELENIUM&&!f){let _=ou({canary:u});!h&&_[t]&&(m=[...m,_[t]]),h&&Me(h)&&(m=[...m,h]),m.length||Fi.warn("No extension was loaded in LambdaTestService",{extUrls:_,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&Me(g)&&(m=[...m,g]);let v=hs(e.project||""),T={euc1:"eu"}[v],w=T?{region:T}:{};return{build:r,name:`${i} - ${n}`,...w,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.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()}}},hS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey","macOS Catalina","macOS Big Sur"])});var Og,yS,Lo,lu=I(()=>{"use strict";Y();Og=["platformName","platform","app","bundleId","appPackage","extensions"],yS=["selenium_version","protocol","host","port","path","build"],Lo=(s,e)=>{let t=e==="lambdaTest"?[...Og,...yS]:Og,r=[],i=[s];for(;i.length;){let n=i.pop();for(let[o,a]of Object.entries(n))t.includes(o)&&r.push(o),a&&typeof a=="object"&&i.push(a)}if(r.length)throw new x(`Custom capabilities contains forbidden keys: ${r.join(", ")}`)}});function TS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Bg(s){return Ng.readFileSync(s,{encoding:"base64"})}function jg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&Me(s))&&s){let r=Bg(s);bs.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${du(r)} current extension count: ${e.length}`),e.push(r)}}function $g(s,e,t,r,i){if(i!=null&&i.isLambdatestRun())return;let n=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!n){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;bs.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&n&&(a=Do.basename(n));let c=Do.join(process.cwd(),a),l=Bg(c);bs.info(`adding extension: testim zipped, path: ${c} length: ${l.length} hash: ${du(l)} current extension count: ${e.length}`),e.push(l)}function wS(s,e,t,r,i,n,o,a){var g,y;let c=t.seleniumName||t.browserValue,l=[],d=[...Ug];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":uu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":uu.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(pu(i)){let v=O.flags.DFAcceptInsecureOrigins.getValue();typeof v=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${v}`),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}pu(i)&&c==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(v=>d.push(`--${v}`));try{let v=No();v.length&&v.forEach(b=>d.push(`--disable-features=${b}`))}catch{}e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=uu.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+Uc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),jg(r,l,o),a===K.EXTENSION&&$g(e,l,d,n,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 ne.isLambdatestGrid(i)&&delete m.w3c,e.oldCapabilities&&i.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||i.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function SS(s,e,t){let r={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Lg.join(","),"browser.helperApps.neverAsk.openFile":Lg.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 ys(s){return`${s.width}x${s.height}`}function CS(s){let{platform:e}=s;if(!e)return ys(Dg);let t=e.split(" ")[1];return e.startsWith("Windows")&&AS.has(t)?ys(IS):e==="Linux"?ys(ES):e.startsWith("macOS")?ys(RS):ys(e==="OS X El Capitan"||e==="OS X Yosemite"?xS:Dg)}function PS(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let i={"sauce:options":{name:e}};if(i["sauce:options"].screenResolution=CS(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 n=(0,Fg.cloneDeep)(t.sl);return delete n.screenResolution,t.browserValue!=="safari"&&delete n.safari_version,et.merge(n,i,r)}return et.merge(i,r)}return{}}function kS(s){let{runnerOptions:e}=s;if(et.isEmpty(e.browserstack))return{};let{projectData:t,testRunConfig:r,testId:i,testName:n,executionId:o,executionName:a}=s,c={buildName:`${a} - ${o}`,sessionName:`${n} - ${i}`,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 OS(s){return s.perfecto?s.perfecto:{}}function _S(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 LS(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:i}=s,n=r||t.user||e.user,o=i||t.key||e.key,a={};return n&&o&&(a.Authorization=gc(n,o)),a}function No(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function Mo(s){var _,B,V,S;let{overrideConfiguration:e,browserOptions:t,testId:r,testName:i,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:d,testResultId:m,lambdatestService:u,mode:f,customCapabilities:h}=s;if(o.mode==="local"){let C=[],D=[...Ug],j={};t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let H=No();H.length&&H.forEach(G=>D.push(`--disable-features=${G}`))}catch{}return t.chromeExtraArgs&&t.chromeExtraArgs.forEach(H=>D.push(`--${H}`)),t.chromeBinaryLocation&&(j.binary=t.chromeBinaryLocation),f!==K.SELENIUM&&$g(t,C,D,null,u),jg(a,C,u),{logLevel:_g,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:C,...j},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:g,driverRequestRetries:y}=t,v=LS(t,o),b={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:_g,connectionRetryTimeout:g,connectionRetryCount:y,getSessionTimeout:Math.max(u.getSessionTimeout,t.getSessionTimeout),getSessionRetries:u.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!et.isEmpty(v)&&{headers:v},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};pu(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 T=Number(t.browserTimeout/1e3),w=t.browser||(n==null?void 0:n.browserValue),E={runnerOptions:t,testId:r,testName:i,testRunConfig:n,executionId:c,executionName:l,projectData:d};et.merge(b.desiredCapabilities,PS(t,i,n),kS(E),OS(t),_S(t,w,T),u==null?void 0:u.getCapabilities(t,w,c,m,i,n,e,f));let A=null;switch(!t.ext&&!t.extensionPath&&((_=o.host)!=null&&_.endsWith(".testim.io"))&&!t.canary&&f===K.EXTENSION&&(w==="chrome"||w==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(A="/opt/testim-headless"),w){case"chrome":case"edge-chromium":b=vS(b,t,n,a,o,A,u,f);break;case"firefox":b=SS(b,t,u);break;case"safari":case"safari technology preview":b=TS(b,w);break;default:break}h?(Lo(h,o.type),et.merge(b.desiredCapabilities,h)):et.merge(b.desiredCapabilities,t.seleniumCapsFileContent);try{let C={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=J=>J[o.provider]||J[b.host]||J[C[b.host]],j=J=>{var xe,Te;return D(J)||J[(xe=b.desiredCapabilities)==null?void 0:xe.browserName]||J[(Te=b.desiredCapabilities)==null?void 0:Te.version]||J||{}},H=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),G=j(j(H));Object.keys(G).length&&(bs.info(`Adding custom capabilities: ${JSON.stringify(G)}`),Object.assign(b.desiredCapabilities,G))}catch(C){bs.error("Failed to load custom capabilities",{error:C,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(b.desiredCapabilities&&!b.capabilities&&(bS(b),b.capabilities={alwaysMatch:b.desiredCapabilities,firstMatch:[{}]},delete b.desiredCapabilities),b.hostname=b.host,s.printFinalCaps){let C=(B=b.capabilities)==null?void 0:B.alwaysMatch,D=JSON.parse(JSON.stringify(b)),j=(V=D==null?void 0:D.capabilities)==null?void 0:V.alwaysMatch,H=J=>J.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(J=>{var xe,Te;j!=null&&j[J]&&(j[J].extensions=(Te=(xe=C==null?void 0:C[J])==null?void 0:xe.extensions)==null?void 0:Te.map(H))}),j!=null&&j.loadExtension&&(j.loadExtension=(S=C==null?void 0:C.loadExtension)==null?void 0:S.map(H));let G=require("node:util");console.log(G.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return b}var Ng,Do,Mg,et,Fg,bs,_g,uu,Ug,du,pu,bS,vS,Lg,Dg,ES,IS,RS,xS,AS,Fo=I(()=>{"use strict";Ng=R(require("node:fs")),Do=R(require("node:path")),Mg=R(require("node:crypto")),et=R(require("lodash"));F();ae();W();de();oe();_o();lu();Fg=require("lodash"),bs=P("testim-desired-capabilities-builder"),_g=In?"debug":"silent",uu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Ug=["--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"],du=(...s)=>Mg.createHash("sha256").update(s.join("")).digest("hex"),pu=s=>s.type===N.DEVICE_FARM||s.type===N.HYBRID&&s.provider==="devicefarm",bS=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 i=JSON.parse(t);if(!Array.isArray(i))return;i.forEach(n=>{delete e[n]})}catch{bs.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};vS=et.memoize(wS,(s,e,t,r,i,n)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(et.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(i.type);return du(o,a,c,r,l,n)}),Lg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Dg={width:1920,height:1080},ES={width:1920,height:1200},IS={width:2560,height:1600},RS={width:2360,height:1770},xS={width:2048,height:1536},AS=new Set(["7","8","8.1","10","11"])});function Be(s){var e,t,r,i,n,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"||((i=s.message)==null?void 0:i.match(/did not match a known command/))||((n=s.message)==null?void 0:n.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 Vg(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 mu=I(()=>{"use strict"});function fu(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 i(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function n(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 n(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=n(u,"stroke-width");return!!g&&parseInt(g,10)>0}return n(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 n(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 fu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(n(s,"visibility")!=="visible")return!1;let d=!!i(s,u=>Number(n(u,"opacity"))===0),m=!!i(s,u=>n(u,"display")==="none");return!(d||m||!o(s)||c(s))}var Gg=I(()=>{"use strict"});var Hg,qg,Ht,DS,NS,Uo,zg=I(()=>{"use strict";Hg=R(require("promise-queue")),qg=R(require("webdriverio"));ae();We();F();W();Vr();Gg();mu();gs();Ht=P("WebDriverApi"),DS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},NS={implicit:0,pageLoad:1,script:2},Uo=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:i}=this,n=t?t.toString().slice(0,2e3):"";throw Ht.warn("error from selenium",{err:e,testResultId:i,testName:r,crashingFunc:n}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Tc!==void 0&&(e=Tc);let t=1/0;this.queue=new Hg.default(e,t)}async addToQueue(e){var r,i;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(n){return this.rejectWithLog(n,e)}finally{(i=this.seleniumPerfStats)==null||i.markEnd(t)}}async initClient(e,t,r){var o,a,c,l,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let i=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(l=(c=e.capabilities.alwaysMatch)==null?void 0:c["goog:chromeOptions"])==null?void 0:l.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),n=(u=this.seleniumPerfStats)==null?void 0:u.markStart(Oe.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t,extUrl:i}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await qg.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(n,Oe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",i="N/A",n;try{n=await this.client.status();for(let a of n.nodes||[])for(let c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){r=a,i=c;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.info("grid status",{gridStatusMsg:n.message,ready:n.ready,browserNode:r,gridSlot:i,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 i=a=>{throw Object.assign(a,{executedScript:e}),a},n=()=>this.client.execute(e,t).catch(i),o=()=>this.client.executeScript(e,t).catch(i);if(this.unsupportedActions.has("execute"))return n();t=t.map(a=>{if(a===null){Ht.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(Be(a))return this.unsupportedActions.add("execute"),n();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 i=()=>this.client.executeAsync(e,...t),n=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return i();try{return await n()}catch(o){if(Be(o))return this.unsupportedActions.add("executeAsync"),i();throw o}})}}async executeCDP(e,t={}){var i;if(!this.isChromium())return;let r=await((i=this.client)==null?void 0:i.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 n;return(n=this.client)==null?void 0:n.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(i=>({value:i})),r=()=>this.execute(fu,{ELEMENT:e,[Kt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(i){if(Be(i))return this.unsupportedActions.add("elementIdDisplayed"),r();throw i}})}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(Vg(e,this.isSafari(),Ht))})}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 n=[];return n[NS[e]]=t,this.client.setTimeouts(...n)},i=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return i();try{return await r()}catch(n){if(Be(n))return this.unsupportedActions.add("timeouts"),i();throw n}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(i,n){window.scrollTo(i,n)};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(DS);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 n;return(n=this.client)==null?void 0:n.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 n;let t=await((n=this.client)==null?void 0:n.$(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 n;return(n=this.client)==null?void 0:n.$(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 i;return(i=this.client)==null?void 0:i.$(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 i={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(i,"yoffset")&&(i.yOffset=1),this.isSafari()&&!Object.hasOwn(i,"xoffset")&&(i.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let n=await this.client.$(e);await this.client.action("pointer").move({origin:n}).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(),i=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let n=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(n,o),i=async()=>await this.client._setWindowSize(n,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await i()}catch(n){if(Be(n))return this.unsupportedActions.add("windowHandleSize"),r();throw n}})}}setCookie(e,t,r,i,n,o,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:i,secure:n,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){Ht.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 Ht.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 or={};z(or,{getSessionPlayer:()=>ee,options:()=>hu});var Bo,hu,gu,ee,ve=I(()=>{"use strict";Bo=require("path");W();hu={playerPath:void 0},ee=()=>{if(gu)return gu;let s=(We(),ze($e));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(pi(),ze(ui)),t=e(),r=hu.playerPath?(0,Bo.resolve)(hu.playerPath,"src/background/sessionPlayerInit.ts"):(0,Bo.join)(t,"sessionPlayer.js"),i=require(r);return s.log("getSessionPlayerRequire end"),gu=i,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&i.setLoggerFormatter&&i.setLoggerFormatter(Yd),i}});var Kg={};z(Kg,{doubleClick:()=>MS});var MS,Jg=I(()=>{"use strict";MS=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let i=s.events,n={status:"done",success:!0};window.__unloadNavigator=function(){e(n)};let o=function(u){function f(b,T,w){return w>b&&w<T}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,v=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:v}},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{i.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(n)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Bi={};z(Bi,{dispatchFocus:()=>FS});function FS(s,e){function t(n){let o=document.createEvent("HTMLEvents");return o.initEvent(n,!0,!1),o}function r(){var o;let n=document.activeElement;for(;(o=n.shadowRoot)!=null&&o.activeElement;)n=n.shadowRoot.activeElement;return n}function i(n,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),n.dispatchEvent(t("focusin")),n.dispatchEvent(t("focus")),typeof n.focus=="function"&&n.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let n=getLocatedElement(s);if(n&&n!==e)try{i(n,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var ji=I(()=>{"use strict"});var eh={};z(eh,{WebDriver:()=>_r});async function $S(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 BS(r):void 0}catch(r){je.info("Error getting cdpAddress",r);return}}var Ts,Qg,Zg,je,ar,US,Xg,BS,kr,jS,Yg,Or,_r,$i=I(()=>{"use strict";Ts=R(require("lodash"));F();We();Fo();Qg=R(require("p-retry")),Zg=R(require("ua-parser-js"));Vr();W();mu();zg();Y();de();gs();je=P("webdriver"),[ar,US]=[0,2],{extractElementId:Xg,getCdpAddressForHost:BS}=Q,kr=()=>(ve(),ze(or)).getSessionPlayer().codeSnippets,jS=()=>(ve(),ze(or)).getSessionPlayer().locatorBuilderUtils,Yg=()=>(ve(),ze(or)).getSessionPlayer().utils,Or=()=>(ve(),ze(or)).getSessionPlayer().positionUtils;_r=class extends Uo{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,V,S,C,D,j,H;let{projectData:r,overrideConfiguration:i,browserOptions:n,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:u,testResultId:f,seleniumPerfStats:h,fastInit:g,lambdatestService:y,printFinalCaps:v,mode:b,customCapabilities:T}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((V=(B=(_=n==null?void 0:n.company)==null?void 0:_.activePlan)==null?void 0:B.premiumFeatures)==null?void 0:V.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let w=Mo({projectData:r,browserOptions:n,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:u,testResultId:f,lambdatestService:y,overrideConfiguration:i,printFinalCaps:v,mode:b,customCapabilities:T});w.desiredCapabilities&&delete w.desiredCapabilities.marionette,w.capabilities&&delete w.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(y==null?void 0:y.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=h;let E=g?0:1500,A=g?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let G=await this.initClient(w,a,f);M("after initResult before getCdpAddress in init"),this.cdpUrl=await $S(G),M("after getCdpAddress in webdriver.js init"),je.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await pe(E),O.flags.dontFocusOnInit.isEnabled()||await A(),M("after focus and delay in webdriver.js init")}catch(G){let J=JSON.stringify(Ts.omit(w,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));je.error("failed to init webdriver",{err:G,capabilitiesAsString:J});let xe=((C=(S=n==null?void 0:n.company)==null?void 0:S.activePlan)==null?void 0:C.plan)==="free";throw(D=G.stack)!=null&&D.includes("at startWebDriverSession")&&((j=G.message)!=null&&j.startsWith("Failed to create session"))&&((H=G.message)!=null&&H.includes("Timeout awaiting 'request'"))&&xe?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(G.message)?new Hr(G.message):/capabilit(y|ies)/.test(G.message)?new Pn(G.message):/403 Forbidden/.test(G.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(G.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${G.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=n=>Ts.zip(n.slice(0,-1),n.slice(1)),r=this._keepAliveRequests.map(({start:n})=>n).filter(Boolean),i=t(r).map(([n,o])=>o-n);return Math.max(...i)}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(i=>t.message.includes(i))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),i=(a,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function n(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=se();r(o);try{await this.executeJS(n),this._isAlive=!0,i("end",o),this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0}catch(a){if(i("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,je.warn("close unexpected alert open"),await this.alertAccept().catch(c=>je.warn("failed to click on alert",{err:c}));return}if(je.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;je.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(i=>{try{i(r)}catch{}})}async switchToLocatedFrame(t){let r=await this.getElement(t),i=Xg(r.value);return await this.switchToFrame({ELEMENT:i,[Kt]:i}),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 kn:r}}async getElement(t){var n;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(((n=t==null?void 0:t.shadowPath)==null?void 0:n.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
19
+ var fn = ${kr().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,...i){return await this.timeouts("script",r),await this.executeAsync(t,...i)}async markDynamicParent(t,r){function i({attributeName:n,attributeValue:o,locatedElement:a}){let c=getLocatedElement(a);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(n,o)}await this.executeJS(`
22
- var getLocatedElement = ${Or().getLocatedElementCode};
22
+ var getLocatedElement = ${kr().getLocatedElementCode};
23
23
  var setDynamicParentAttribute = ${i.toString()};
24
24
  return setDynamicParentAttribute.apply(null, arguments)
25
- `,{attributeName:WS().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(i){let n=getLocatedElement(i);if(!n)return null;let o=parseInt(window.getComputedStyle(n).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(n).paddingLeft.replace("px",""),10)||0,c=n.getBoundingClientRect();return{top:Math.round(c.top+o),left:Math.round(c.left+a)}}return this.executeJS(`
26
- const getLocatedElement = ${Or().getLocatedElementCode};
25
+ `,{attributeName:jS().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(i){let n=getLocatedElement(i);if(!n)return null;let o=parseInt(window.getComputedStyle(n).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(n).paddingLeft.replace("px",""),10)||0,c=n.getBoundingClientRect();return{top:Math.round(c.top+o),left:Math.round(c.left+a)}}return this.executeJS(`
26
+ const getLocatedElement = ${kr().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(i){let n=getLocatedElement(i);if(!n)return null;let o=n.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 = ${Or().getLocatedElementCode};
30
+ const getLocatedElement = ${kr().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(n,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,b=>b.hidden).forEach(b=>y.removeChild(b)),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(n);return m?d(m):""}let{value:i}=await this.executeJS(`
34
- const getLocatedElement = ${Or().getLocatedElementCode};
34
+ const getLocatedElement = ${kr().getLocatedElementCode};
35
35
  const extractText = ${r.toString()};
36
36
  return extractText.apply(null, arguments)
37
- `,t,this.ignoreHiddenTagsText);return i}async getHTML(t){var n,o;let r=Or().getHtmlCode(void 0,t),i=this.seleniumPerfStats.markStart(Oe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(i,Oe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(i,Oe.GET_HTML);let c=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(o=(n=this.client)==null?void 0:n.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 n extends Error{}function o(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,th.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 n},{retries:5-1,factor:1,minTimeout:0}).catch(l=>{if(!(l instanceof n))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(i){return je.error("failed to get browser version",{err:i}),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:i}=await this.executeJS(r),n=(0,rh.default)(i),o=n.os;return this.browserAndOS={os:`${o.name} ${o.version}`,browserMajor:this.getBrowserMajorVersion(n),browser:t(i),userAgent:i,browserVersion:n.browser.version},this.browserAndOS}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:i,clickOffset:n}=t,o=_r().calculateElementMiddlePoint(i),a=n.x,c=n.y;return!eh().isWithinBounds(i.left,i.left+i.width,o.x+a)||!eh().isWithinBounds(i.top,i.top+i.height,o.y+c)?(je.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,c,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:i,clickOffset:n}=t,o=i.left+n.x+r.x,a=i.top+n.y+r.y;return{x:o,y:a}}async actWithActionsAPI(t,r,i,n){let o=this.getRelativeMoveActions(t,i),a=this.getClickActions(n,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(a)}])}catch(c){je.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,ar,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:i}]=await Promise.all([Promise.resolve().then(()=>(Qg(),Xg)),Promise.resolve().then(()=>($i(),ji))]);return this.executeCodeAsync(`
38
- var getLocatedElement = ${Or().getLocatedElementCode};
37
+ `,t,this.ignoreHiddenTagsText);return i}async getHTML(t){var n,o;let r=kr().getHtmlCode(void 0,t),i=this.seleniumPerfStats.markStart(Oe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(i,Oe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(i,Oe.GET_HTML);let c=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(o=(n=this.client)==null?void 0:n.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 n extends Error{}function o(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,Qg.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 n},{retries:5-1,factor:1,minTimeout:0}).catch(l=>{if(!(l instanceof n))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(i){return je.error("failed to get browser version",{err:i}),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:i}=await this.executeJS(r),n=(0,Zg.default)(i),o=n.os;return this.browserAndOS={os:`${o.name} ${o.version}`,browserMajor:this.getBrowserMajorVersion(n),browser:t(i),userAgent:i,browserVersion:n.browser.version},this.browserAndOS}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:i,clickOffset:n}=t,o=Or().calculateElementMiddlePoint(i),a=n.x,c=n.y;return!Yg().isWithinBounds(i.left,i.left+i.width,o.x+a)||!Yg().isWithinBounds(i.top,i.top+i.height,o.y+c)?(je.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,c,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:i,clickOffset:n}=t,o=i.left+n.x+r.x,a=i.top+n.y+r.y;return{x:o,y:a}}async actWithActionsAPI(t,r,i,n){let o=this.getRelativeMoveActions(t,i),a=this.getClickActions(n,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(a)}])}catch(c){je.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,ar,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:i}]=await Promise.all([Promise.resolve().then(()=>(Jg(),Kg)),Promise.resolve().then(()=>(ji(),Bi))]);return this.executeCodeAsync(`
38
+ var getLocatedElement = ${kr().getLocatedElementCode};
39
39
  var dispatchFocus = ${i.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(i=>({type:i,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,ar,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,jS,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(i){if(Be(i))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw i}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(i){if(Be(i))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw i}}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 i=await this.getLocatedElementRect(t);if(!(i!=null&&i.value))throw je.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:n,y:o,width:a,height:c}=i.value;return{x:r.left+n+a/2,y:r.top+o+c/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:i,y:n}=r.clickOffset;try{return await this.moveTo(t,i,n)}catch(o){if(Be(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,i="viewport",n=0){return[{type:"pointerMove",duration:n,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:i}]}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(i){je.error("tried to use element origin but failed because of visibility, trying location",i);let n=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(n)}}getDragCoordinates(t){let r=t.filter(o=>o.event==="mousemove"||o.event==="pointermove"),i=r[0].pointerPosition,n=r.at(-1).pointerPosition;return{xDiff:n.screenX-i.screenX,yDiff:n.screenY-i.screenY}}async dragWithMoveTo(t,r,i,n,o){return await this.moveTo(t,n,o),await this.buttonDown(),await this.moveTo(t,r,i),await this.buttonUp()}dragWithActionsAPI(t,r,i,n,o){let a=this.getMoveActions(n,o,t,1),c=this.getClickActions(["pointerDown"],ar),l=this.getMoveActions(r,i,"pointer",1),d=this.getClickActions(["pointerUp"],ar);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(c).concat(l).concat(d)}])}async drag(t,r,i,n,o){let{width:a,height:c}=r,l=i-a/2+1,d=n-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(Be(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,l,d);throw h}}getMoveRelativeSequence(t,r,i,n){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},c={x:i,y:n},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,i,n){return this.getMoveRelativeSequence(t,r,i,n).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,i){let{fromRect:n,fromX:o,fromY:a,toRect:c,toX:l,toY:d}=i,m=_r().calculateElementMiddlePoint(n),u=_r().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:i,fromY:n,toRect:o,toX:a,toY:c}=t,l=_r().calculateElementMiddlePoint(r),d=_r().calculateElementMiddlePoint(o),m=Math.floor(l.x+i),u=Math.floor(l.y+n),f=Math.floor(d.x+a),h=Math.floor(d.y+c),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),v=this.getClickActions(["pointerDown"],ar),b=Ss.flatMap(g,C=>this.getMoveActions(C.x,C.y)),T=this.getMoveActions(f,h),w=this.getClickActions(["pointerUp"],ar),E=y.concat(v).concat(b).concat(T).concat(w);return this.actions([{type:"pointer",id:"mouse",actions:E}])}async dragAndDrop(t,r,i){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(i);try{return await this.dragAndDropWithGeneratedMoves(t,r,i)}catch(n){if(Be(n))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(i);throw n}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(i);try{return await this.dragAndDropOldAPI(t,r)}catch(n){if(Be(n))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(i);throw n}}doubleClickFallback(t,r,i){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,i)}async doubleClick(t,r,i){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,i);try{return await this.doDoubleClick(t)}catch(n){if(Be(n))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,i);throw n}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:i,fromY:n,toRect:o,toX:a,toY:c}=t,l=_r().calculateElementMiddlePoint(r),d=_r().calculateElementMiddlePoint(o),m=Math.floor(l.x+i),u=Math.floor(l.y+n),f=Math.floor(d.x+a),h=Math.floor(d.y+c);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],ar);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],ar);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(Zg(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},i;try{i=await this.getElementLocation(t)}catch(n){je.error("error getting element location",{err:n})}return i!=null&&i.value?{top:i.value.y,left:i.value.x,width:i.value.width,height:i.value.height}:r}async end(){je.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||je.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(Be(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var vu,Su,Vi,Eu=I(()=>{"use strict";W();de();ge();vu=P("lab-features-service"),Su=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(vu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),i=r?await Iu(e):[];this.featuresForProject=i,this.labBatman=r}catch(r){vu.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:i,labBatman:n}=this,o=i.find(c=>c.featureFlagName===e),a=o==null?void 0:o.enabled;return Boolean(n&&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 vu.error(t,{featureFlagName:e.name}),new Error(t)}},Vi=new Su});function GS(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function HS(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:i}=globalThis.require("fs");return{sync:!1,lib:i.readFile(`${s}${t}package.json`).then(o=>{let a=JSON.parse(o);return import(r(s,a.main||`${t}index.js`))})}}}function qS(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function zS(s,e,t,r,i={},n=void 0,o=void 0){let a=Object.keys(i).map(h=>`
45
- var res = requireOrImportMethod('${GS(i[h])}');
44
+ `,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(i=>({type:i,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,ar,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,US,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(i){if(Be(i))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw i}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(i){if(Be(i))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw i}}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 i=await this.getLocatedElementRect(t);if(!(i!=null&&i.value))throw je.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:n,y:o,width:a,height:c}=i.value;return{x:r.left+n+a/2,y:r.top+o+c/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:i,y:n}=r.clickOffset;try{return await this.moveTo(t,i,n)}catch(o){if(Be(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,i="viewport",n=0){return[{type:"pointerMove",duration:n,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:i}]}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(i){je.error("tried to use element origin but failed because of visibility, trying location",i);let n=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(n)}}getDragCoordinates(t){let r=t.filter(o=>o.event==="mousemove"||o.event==="pointermove"),i=r[0].pointerPosition,n=r.at(-1).pointerPosition;return{xDiff:n.screenX-i.screenX,yDiff:n.screenY-i.screenY}}async dragWithMoveTo(t,r,i,n,o){return await this.moveTo(t,n,o),await this.buttonDown(),await this.moveTo(t,r,i),await this.buttonUp()}dragWithActionsAPI(t,r,i,n,o){let a=this.getMoveActions(n,o,t,1),c=this.getClickActions(["pointerDown"],ar),l=this.getMoveActions(r,i,"pointer",1),d=this.getClickActions(["pointerUp"],ar);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(c).concat(l).concat(d)}])}async drag(t,r,i,n,o){let{width:a,height:c}=r,l=i-a/2+1,d=n-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(Be(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,l,d);throw h}}getMoveRelativeSequence(t,r,i,n){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},c={x:i,y:n},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,i,n){return this.getMoveRelativeSequence(t,r,i,n).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,i){let{fromRect:n,fromX:o,fromY:a,toRect:c,toX:l,toY:d}=i,m=Or().calculateElementMiddlePoint(n),u=Or().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:i,fromY:n,toRect:o,toX:a,toY:c}=t,l=Or().calculateElementMiddlePoint(r),d=Or().calculateElementMiddlePoint(o),m=Math.floor(l.x+i),u=Math.floor(l.y+n),f=Math.floor(d.x+a),h=Math.floor(d.y+c),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),v=this.getClickActions(["pointerDown"],ar),b=Ts.flatMap(g,A=>this.getMoveActions(A.x,A.y)),T=this.getMoveActions(f,h),w=this.getClickActions(["pointerUp"],ar),E=y.concat(v).concat(b).concat(T).concat(w);return this.actions([{type:"pointer",id:"mouse",actions:E}])}async dragAndDrop(t,r,i){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(i);try{return await this.dragAndDropWithGeneratedMoves(t,r,i)}catch(n){if(Be(n))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(i);throw n}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(i);try{return await this.dragAndDropOldAPI(t,r)}catch(n){if(Be(n))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(i);throw n}}doubleClickFallback(t,r,i){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,i)}async doubleClick(t,r,i){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,i);try{return await this.doDoubleClick(t)}catch(n){if(Be(n))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,i);throw n}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:i,fromY:n,toRect:o,toX:a,toY:c}=t,l=Or().calculateElementMiddlePoint(r),d=Or().calculateElementMiddlePoint(o),m=Math.floor(l.x+i),u=Math.floor(l.y+n),f=Math.floor(d.x+a),h=Math.floor(d.y+c);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],ar);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],ar);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(Xg(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},i;try{i=await this.getElementLocation(t)}catch(n){je.error("error getting element location",{err:n})}return i!=null&&i.value?{top:i.value.y,left:i.value.x,width:i.value.width,height:i.value.height}:r}async end(){je.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||je.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(Be(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var yu,bu,Wi,Tu=I(()=>{"use strict";W();de();ge();yu=P("lab-features-service"),bu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(yu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),i=r?await wu(e):[];this.featuresForProject=i,this.labBatman=r}catch(r){yu.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:i,labBatman:n}=this,o=i.find(c=>c.featureFlagName===e),a=o==null?void 0:o.enabled;return Boolean(n&&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 yu.error(t,{featureFlagName:e.name}),new Error(t)}},Wi=new bu});function WS(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function VS(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:i}=globalThis.require("fs");return{sync:!1,lib:i.readFile(`${s}${t}package.json`).then(o=>{let a=JSON.parse(o);return import(r(s,a.main||`${t}index.js`))})}}}function GS(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function HS(s,e,t,r,i={},n=void 0,o=void 0){let a=Object.keys(i).map(h=>`
45
+ var res = requireOrImportMethod('${WS(i[h])}');
46
46
  if (res.sync) {
47
47
  var ${h} = res.lib;
48
48
  } else {
49
49
  var ${h} = await res.lib;
50
50
  }
51
51
  `).join(""),c=o?`
52
- ${oh.default.toString()}
52
+ ${sh.default.toString()}
53
53
  var fileBuffer = dataUriToBuffer('${o}');
54
54
  `:"var fileBuffer = null;",l=`
55
55
  const getMessage = arguments => {
@@ -105,7 +105,7 @@ Testim had missing write access to ${r||e}
105
105
  });
106
106
  `,d=`
107
107
  function injectCode(params, args, incomingParams, context, code) {
108
- const constructWithArguments = ${qS.toString()}
108
+ const constructWithArguments = ${GS.toString()}
109
109
 
110
110
  const resolve = result => {
111
111
  parentPort.postMessage({
@@ -171,7 +171,7 @@ Testim had missing write access to ${r||e}
171
171
  // A hack to fix an issue with stringified functions which use require. when compiling to JS, calls to require change to __require.
172
172
  const __require = require;
173
173
  const { parentPort } = require('worker_threads');
174
- const requireOrImportMethod = ${HS.toString()}
174
+ const requireOrImportMethod = ${VS.toString()}
175
175
 
176
176
  // requireCode will set async to be true if needed.
177
177
  ${a}
@@ -180,7 +180,7 @@ Testim had missing write access to ${r||e}
180
180
 
181
181
  ${l}
182
182
 
183
- const isPromise = ${Ac.toString()}
183
+ const isPromise = ${Ic.toString()}
184
184
 
185
185
  parentPort.once('message', input => {
186
186
  const { incomingParams, context, code } = input;
@@ -209,73 +209,73 @@ 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 le(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,v={...y,tstConsoleLogs:u};ft.debug("Run code worker response",{messageWithLogs:v,transactionId:s}),h(v)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?ft.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):ft.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",()=>{ft.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),n)}catch(h){if(!(h instanceof ce))throw h;return ft.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 KS(s){try{await ih.promises.rm(s,{recursive:!0,force:!0})}catch(e){ft.warn("failed to remove install npm packages folder",{err:e})}}function ch(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function Is(s,e,t,r,i,n){let o=ch(i,e,s,t),{data:a}=await JS(o,r,n);return a}async function Rs(s,e,t,r,i,n,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 v=Jm(y.testimPackageLocalLocation);return[y.paramName,Es.join(y.testimPackageLocalLocation,v)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=ch(o,i,e,n);if(l){let y=await Di(l);y&&(c=y)}Buffer.isBuffer(c)&&(ft.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let f="data:,";return c==="data:"&&(ft.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=f),{...await zS(u,t,r,s,m,a,c),nodeVersion:process.version}}async function JS(s,e,t){let r=e.map(l=>`${l.packageName}@${l.packageVersion}`),i=lh(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?i:Es.join(i,`/${s}`),a=global.proxyUri;async function c(){let l="";try{if(l=await nl(o,r,a,t),ft.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=zm(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:Es.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw ft.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await le(c(),t)}catch(l){throw l instanceof ce&&ft.warn("timeout to install package",{packages:r,transactionId:s,err:l,timeout:t}),l}}function lh(){return Es.join(nh.tmpdir(),"/testim_local_packages")}function YS(){let s=lh();return KS(s)}var ih,nh,Es,oh,ah,ft,xs=I(()=>{"use strict";ih=R(require("fs")),nh=R(require("os")),Es=R(require("path"));F();as();oh=R(require("data-uri-to-buffer")),ah=require("worker_threads");X();W();ge();as();de();ft=P("cli-service");YS().catch(s=>ft.warn("failed to clean local package folder",{err:s}))});var cr={};z(cr,{run:()=>QS});function XS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),i=JSON.stringify(s).length>r;return t?i:!1}catch{return!1}}var QS,uh=I(()=>{"use strict";xs();X();de();QS=async(s,e,t)=>{let{code:r,stepId:i,incomingParams:n,context:o,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await Rs(r,i,n,o,a,c,l,d,m,u);return f&&XS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ce?new Error("Timeout while running action"):f}}});var Ru={};z(Ru,{run:()=>ZS});var ZS,ph=I(()=>{"use strict";xs();X();ZS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:i,stepResultId:n,packageData:o,timeout:a}=e.data;try{return{data:await Is(t,r,i,o,n,a),success:!0}}catch(c){if(c instanceof Pt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof ce)return{success:!1,code:"timeout"};throw c}}});async function mh(s,e,t,r){try{return await xu(s,e,t,r)}catch{$o.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function tE(s,e,t,r,i){return $o.info("finished to run remote step",{stepId:t,sessionId:i}),await mh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function dh(s,e,t,r,i){return $o.info("failed to run remote step",{stepId:t,sessionId:i,failureReason:r}),await mh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function fh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:i,projectData:n}=s,o=t.type,a=e.getSessionId(),c=t.id;$o.info("start play remote step",{stepType:o,stepId:c,sessionId:a});let l=eE[o];if(!l)return await dh(i,r,c,`Failed to find step type ${o}`,a);try{let d=await l.run(e,t,n);return await tE(i,r,c,d,a)}catch(d){return await dh(i,r,c,d.message,a)}}var $o,eE,gh=I(()=>{"use strict";uh();ge();ph();W();$o=P("step-playback"),eE={"cli-validation-code-step":cr,"cli-wait-for-code-step":cr,"cli-action-code-step":cr,"cli-api-code-step":cr,"cli-condition-step":cr,"cli-download-code-step":cr,"node-package":Ru}});var yh={};z(yh,{preloadTests:()=>Hi});async function Hi(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await Ot(async()=>{let t=await ie(s.testId,r=>qi({...e,testId:r}),{concurrency:2});return hh.keyBy(t,"testData.id")},"loadTests",sE,[e,s.testId])()}var hh,sE,Wo=I(()=>{"use strict";hh=R(require("lodash"));er();ge();F();sE=1e3*60*60*10});var Cu,bh,Lr,iE,Au,vt,Vo=I(()=>{"use strict";F();ut();Cu=R(require("ws")),bh=require("events");W();oe();Lr=P("socket-service"),iE=5e3,Au=class extends bh.EventEmitter{constructor(){super(...arguments);this.clientId=se();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Lr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),iE)}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){Lr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(_d);return _t().then(i=>new Promise(n=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Cu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${i}`,o),this.ws.on("open",()=>{var a;return Lr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),n()}),this.ws.on("close",a=>{Lr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Cu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Lr.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){Lr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Lr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,i){let n=o=>{r(o)&&(i(o),this.removeListener(t,n))};this.on(t,n)}listenTo(t,r,i,n){function o(c){i(c)&&n(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,i,n=!1){return new Promise(o=>{let a=se(),c={query:r,id:a,type:i,fullDocument:n};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(i=>{let n=this.listeners[`${t}:${i}`];n&&(delete this.listeners[`${t}:${i}`],n.forEach(o=>this.removeListener(i,o)))})}removeFilter(t,r){let i=this.filterMap[t];if(!i)return;let n=Array.isArray(r)?r:[r];this.removeListeners(t,n),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:i})}},vt=new Au});var wh,Pu,nE,oE,aE,Th,Go,Cs,ku=I(()=>{"use strict";wh=R(require("p-retry")),Pu=R(require("socket.io-client"));oe();F();W();nE=50,oE=10,aE=5e3,Th=10*1e3,Go=P("base socket service"),Cs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Go.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var i;let r=this.rooms[t];(i=this.emitJoinRoom)==null||i.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let i="websocket";try{i=this._socket.io.engine.transport.name}catch{}Go.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${i}. 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===oE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=nE)throw new Error(`Can't connect to Testim Servers.
213
- Action required: Please allow opening a websockets connection to ${he()} 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",()=>{Go.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:Th,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(i=>{this.url=`${he()}/${t}`,this._socket=Pu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",i),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Th,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=`${he()}/${t}`,this._socket=Pu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},i=()=>new Promise((n,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?n():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,wh.default)(()=>le(i(),aE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Go.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var vh={};z(vh,{remoteStepServiceSocketIO:()=>cE});var Ou,cE,Sh=I(()=>{"use strict";ku();Ou=class extends Cs{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]=i=>{i.resultId===t&&i.remoteStep&&i.remoteStep.status==="pending"&&r(i.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))}},cE=new Ou});var Eh={};z(Eh,{remoteStepService:()=>As});var _u,zi,Du,As,Ho=I(()=>{"use strict";Vo();ae();de();({REMOTE_STEP_SAVED:_u}=kt),Du=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(zi=(await Promise.resolve().then(()=>(Sh(),vh))).remoteStepServiceSocketIO,zi.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:remoteStep`,{resultId:e},[_u]):zi.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:remoteStep`,[_u],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}zi.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(vt.removeFilter(`${e}:remoteStep`,[_u]),Promise.resolve()):zi.unlistenToRemoteStep(e)}},As=new Du});var Lu,Nr,Ih=I(()=>{"use strict";ku();Lu=class extends Cs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,i){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.testId===r&&i(n.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}},Nr=new Lu});var xh={};z(xh,{testResultService:()=>Nt});var Rh,Nu,Nt,qo=I(()=>{"use strict";Rh=require("events");Vo();ae();de();Ih();Nu=class extends Rh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){vt.onConnect=()=>this.emit("socket-connected");return}Nr.init(e),Nr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[kt.TEST_RESULT_UPDATED,kt.TEST_RESULT_CREATED]):Nr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){vt.removeFilter(`${e}:testResult`,[kt.TEST_RESULT_UPDATED,kt.TEST_RESULT_CREATED]);return}await Nr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:testResult`,[kt.TEST_RESULT_UPDATED,kt.TEST_RESULT_CREATED],i=>i.resultId===e&&i.testId===t,i=>r(i));return}Nr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Nr.getSocket()}},Nt=new Nu});var Ah,Ph,kh,Ie,lE,Oh,Ch,uE,zo,_h=I(()=>{"use strict";Ah=R(require("lodash"));F();oe();We();ps();ut();ge();gh();Ph=R(require("p-retry")),kh=require("node:url");W();Wo();bs();ae();Ho();qo();ge();Ie=P("test-run-handler"),lE=3,Oh=20*1e3,Ch=s=>JSON.stringify(s).length<Oh,uE="Test couldn't be started",zo=class{constructor(e,t,r,i,n,o){this._executionId=e;this._executionName=t;this._options=i;this._branch=n;this._testRunStatus=o;this.seleniumPerfStats=new Pr;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=i.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=i.retries,this._remoteRunId=i.remoteRunId,this._customCapabilities=i.customCapabilities||((l=r.customCapabilities)==null?void 0:l.capabilities);let a=!((d=r.runConfig)!=null&&d.isMobileWeb)&&i.browser;this._runConfig=a?ii(i.browser,i.saucelabs,i.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,i;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:(i=this._nativeApp)==null?void 0:i.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 i,n,o,a;return this.isAppFromDevice?null:r?(n=(i=r.gridData)==null?void 0:i[e])==null?void 0:n[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 si(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Zr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Mn.FROM_DEVICE:Mn.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${he()}/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 qi({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,i;let t={tokenV3:await _t(),refreshToken:so(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Bd(),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 io()};if(this._options.disableMockNetwork&&dt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let n=this.runData,o=Ch(n);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(n).length,c=this.testId;o?(Object.assign(t,{runData:n}),Ie.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Ie.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Oh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((i=this._options.lightweightMode)!=null&&i.preloadTests&&this._options.useChromeLauncher){let n=await Hi(this._options);Object.assign(t,{preloadedTest:n[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Ie.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 n;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((n=this._options.lightweightMode)!=null&&n.disableResults&&!t&&Ch(e))return;let r=async()=>{try{return await Uu(this._options.project,this._testId,this._testResultId,e)}catch(o){return Ie.error("failed to upload run data artifact (runner)",{err:o}),""}},i=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Fu(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=i(),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===uE||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:i}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:n}=t.find(o=>o.type==="page")||{};if(!i)throw new Error("Tricentis Testim extension not found");if(!n)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:i,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=o||{};M("before Runtime.evaluate"),await(0,Ph.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 Ie.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 kh.URL(e)}catch{return}let{username:i,password:n}=r;if(i||n)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,i=n=>{if(!r){if(this.isRetryKeyMismatch(n)){Ie.warn(`ignoring result update for on started due to retry key mismatch, got ${n.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(n.status)&&(n.resultId=this.testResultId,n.status==="completed"&&!this.isRerunOnInfraError(n.reason)&&(Ie.info("setting _wasCompletedOnStartedCheck to true",{testResult:n,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=n),r=!0,t(n))}};if(this._options.disableSockets){let n=Date.now()+e,o=async()=>{if(Date.now()>n)return;let{testId:a,testResultId:c,branch:l,_options:{project:d}}=this;try{let m=await Mr(a,c,d,l);i(m),r||setTimeout(o,3e3)}catch(m){Ie.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else Nt.listenToTestResult(this._testResultId,this._testId,i)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:i}=this;try{let n=await Mr(e,t,r,i),o=["running","completed"];if(o.includes(n.status))return Ie.info(`get status: ${n.status} after not get test started status`,{testId:e,testResultId:t,branch:i}),n;throw Ie.error(`test not start test status: ${n.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:i}),new Error(Pe.TEST_START_TIMEOUT_MSG)}catch(n){throw Ie.error("failed to get test result after test start timeout",{err:n,testId:e,testResultId:t,branch:i}),new Error(Pe.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Nt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Ie.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Nt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Ie.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 i=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),n=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Ah.debounce(async()=>{try{await Nt.joinToTestResult(this._testResultId,this.testId)}catch(o){Ie.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Mr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Ie.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"?(Ie.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 Ie.warn("Error while trying to check status on socket connect",o),!1}},i,{maxWait:n}),!this._options.disableSockets)Nt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Mu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Ie.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Ie.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Nt.off("socket-connected",e)}}listenToRemoteStep(e){As.listenToRemoteStep(this.testResultId,t=>{fh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:lE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Ko,Dh=I(()=>{"use strict";_h();Ko=class{constructor(e,t,r,i,n,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));!i.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),i.appId&&this.pendingAppUploads.set(i.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new zo(e,t,c,i,n,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function Nh(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(i=>({testId:i,testConfig:{},resultId:se()}))]}:await $u({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 Bu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,i)=>r+(s[i].success===!0?1:0),0);return e===t}async function ju(s,e){let t=s.mode===K.EXTENSION?Fr:Ki,r=Lh.difference(ti(s,e),t);if(r.length>0)throw dt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new x(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Lh,Fr,Ki,Jo=I(()=>{"use strict";Lh=R(require("lodash"));F();ps();ge();X();ae();Fr=["edge-chromium","chrome"],Ki=[...Fr,"firefox","safari","safari technology preview"]});var pE,dE,mE,Ji,Wu=I(()=>{"use strict";ls();gs();W();pE=P("worker-utils"),dE=async(s,e,t)=>{e&&await El(s,t)},mE=async(s,e,t)=>{await Jl(s,e,t)},Ji=async(s,e,t,r,i,n)=>{pE.info("releasing player",{hasPlayer:Boolean(n)});try{await(n==null?void 0:n.onDone())}finally{i==="mongo"&&await dE(s,e,t),i==="redis"&&await mE(s,r,t)}}});function yE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Qo,Uh,Zo,ea,Bh,St,Mh,Fh,Yo,Vu,Ur,fE,Gu,gE,qt,hE,Xo,bE,Mt,Yi=I(()=>{"use strict";Qo=R(require("ms")),Uh=R(require("lodash")),Zo=R(require("p-retry")),ea=R(require("dayjs")),Bh=R(require("dayjs/plugin/duration"));F();We();ls();gs();ge();W();Wu();Lt();Do();de();Ho();qo();ut();He();ae();X();ea.default.extend(Bh.default);St=P("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Mh,TEST_START_TIMEOUT_MSG:Fh,TEST_COMPLETE_TIMEOUT_MSG:Yo,TEST_REACHED_CUSTOM_TIMEOUT_MSG:Vu}=Pe,{SETUP_TIMEOUT:Ur,NETWORK_ERROR:fE,GRID_ERROR:Gu,BROWSER_CLOSED:gE,SELENIUM_ERROR:qt,UNKNOWN_ERROR:hE,MOBILE_SESSION_ERROR:Xo}=Xr;bE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Mt=class{constructor(e,t,r,i,n,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=i;this.onTestStarted=n;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new ne;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await Rf(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,i){throw new zs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),St.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!Qe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:fe.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var i,n;if(((i=this.options.gridData)==null?void 0:i.mode)==="local")return;let t=es(O,(n=this.options.gridData)==null?void 0:n.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:fe.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=vr(O.flags.appiumConnectionRequestTimeout.getValue(),(0,Qo.default)("2m")),i=vr(O.flags.appiumConnectionRetryCount.getValue(),1),n=r*i;return e===D.BROWSERSTACK||t&&e===D.TESTIM_TDC?n+(0,Qo.default)("10m"):n+(0,Qo.default)("1m")}getSessionTimeout(){if(Zt(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,Zo.default)(async()=>{let i=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Pe.GET_BROWSER_TIMEOUT_MSG)}catch(n){return t++,await this.handleGetSlotError(n,i)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Zo.default)(async()=>{var i,n;let r=Date.now();try{let o=(i=this.options.company)==null?void 0:i.companyId,a=(n=this.options.projectData)==null?void 0:n.projectId;return await le(Xf(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 Xt?St.info("could not get grid slot due to concurrency issue",r):St.error("error getting grid slot",{error:e,...r}),await pe(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 n;let r=(n=this.userData)==null?void 0:n.projectId,i;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;i=await(0,Zo.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await xf(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===K.APPIUM?"device":"browser";throw St.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,r,++l),m.onDone(),!(u instanceof At)&&this.options.mode!==K.APPIUM&&await pe(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:c-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(o){throw await Ji(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,i),[At,Kr].some(a=>o instanceof a)?o:o instanceof nt?new Tr(o,Gu):new Tr(o,qt)}return i}async runTest(e,t,r){var d;M("inside runTest");let i=(d=this.userData)==null?void 0:d.projectId,n=this.handleQuarantine(e);if(n)return n;let o=Zt(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 _t(),await this.runTestOnce(e,l)}finally{await Ji(this.id,this.releaseSlotOnTestFinished,i,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let i=async(g,y)=>{var N,j;if(Qe(g,this.options)||es(O,(N=this.options.gridData)==null?void 0:N.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let v=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let b=H=>y==null?void 0:y.message.includes(H),T=y&&y instanceof Tr,w=b(Fh),E=y&&(b(Yo)||b(Vu)||w&&!e.retryOnInfraErrors),C=!!b(Vu)&&!!this.testRunTimeout,B=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||w)&&e.retryOnInfraErrors,V=E&&e.hasMoreTimeoutRetries()&&!C,S=e.hasMoreRetries()&&!T&&!E,A=!g.success&&(S||V||B);try{let H=e.retryKey;g.testRetryKey=H;let G=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,v,A,G),await this.runTestCleanup(),A){if(V&&await e.startNewTimeoutRetry(),B){St.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 J=(j=this.options.projectData)==null?void 0:j.projectId,xe=e.testResultId,Te=e.testId;await ta(J,xe,Te,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return S&&!B&&!V&&await e.startNewRetry(),St.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:H,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(A)}t(this.id,...r);return}catch(H){if(H instanceof Yt)return;St.error("failed to process test result",{error:H}),t(this.id,...r);return}},n=()=>`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. ${Fc()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:v,APP_NEVER_STARTED:b,TIMEOUT_ERROR:T,SAUCELABS_APP_IS_NOT_INSTALLED:w}=Hc,E=g instanceof Error?g.message:g;if(E.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),E.includes(Mh)||E.includes(T))return{errorType:Ur,reason:"timeout while getting device"};if(E.includes(Yo)||E.includes(Vu)){if(!this.testRunTimeout)return{errorType:Ur,reason:"Test timeout reached!"};let C=ea.default.duration({milliseconds:this.testRunTimeout});return{errorType:Ur,reason:`Test timeout reached (timeout: ${Bn(C)})`}}return E.includes(v)||E.includes(w)?{errorType:Xo,reason:"app doesn't exist on device"}:E.includes(b)?{errorType:Xo,reason:"app never started, check app permission or app activity"}:E.includes(y)?{errorType:Xo,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Xo,reason:E}},a=(g,y)=>{let v=this.options.mode===K.APPIUM?"device":"browser";if(!y&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:fE,reason:n()};let b=g instanceof Error?g.message:g;if(b.includes(Mh))return{errorType:Ur,reason:`Test couldn't get ${v}`};if(b.includes(Fh))return{errorType:Ur,reason:"Test couldn't be started"};if(g instanceof Tr&&g.type){if(g.type===Gu)return{errorType:Gu,reason:`Test couldn't get ${v} from grid - ${g.message}`};if(g.type===qt)return{errorType:qt,reason:`Failed to create new session - ${g.message}`}}return b.includes(Yo)?this.testRunTimeout?{errorType:Ur,reason:`Test timeout reached (timeout: ${Bn(ea.default.duration({milliseconds:this.testRunTimeout}))})`}:{errorType:Ur,reason:"Test timeout reached: test is too long"}:"type"in g&&g.type===gE?{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 ${v} you requested is supported in your plan`}:{errorType:hE,reason:b}},c=async g=>{var w;let y=await Mc();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(n()),St.warn("error on run",{err:g});let v=(w=this.userData)==null?void 0:w.projectId,{errorType:b,reason:T}=this.options.mode===K.APPIUM?o(g):a(g,y);ta(v,this.testResultId,this.testId,{status:Zs.COMPLETED,success:!1,reason:T,errorType:b,testRetryKey:e.retryKey,setupStepResult:{status:Zs.COMPLETED,success:!1,reason:T,errorType:b}},e.remoteRunId),await i(yE(this.testId,this.testName,this.testResultId,T),g)},l=async g=>{var w;let y=this.testId,v=this.testResultId,b=(w=this.userData)==null?void 0:w.projectId,T=this.branch;if(!y||!v||!b||!T)return St.warn("Test failed. Not enough data to recover results via API",{err:g}),c(g);try{let E=await Mr(y,v,b,T);if(St.warn("Test failed. Got results via API",{err:g,testResult:Uh.default.omit(E,bE),resultId:v}),E&&E.status===Zs.COMPLETED&&!g.message.includes(Yo))return await i(E);throw g}catch(E){return E!==g&&St.error("Failed to fetch test results from server",{testId:y,resultId:v,projectId:b,branch:T,err:E}),c(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===K.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&As.joinToRemoteStep(this.testResultId),!d&&Nt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==K.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await i(y),M("After onRunComplete"),t(this.id,...r)}catch(y){await l(y),t(this.id,...r)}finally{m||As.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 $h,jh,Ps,Hu=I(()=>{"use strict";F();$h=R(require("p-retry"));F();W();X();jh=P("window-utils"),Ps=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(n,o){let a=document.elementFromPoint(n,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:i}=await this.driver.executeJS(r,e,t);return i}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(i=3)=>{try{await this.driver.url(e)}catch(n){let o=n.message.includes("method IWebBrowser2::Navigate2() failed");if(n.seleniumStack&&o&&i>0)return jh.warn("selenium navigation failed. retrying to navigate",{err:n}),await pe(1500),r(i-1);throw!n.seleniumStack&&o&&jh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:n}),n}};return Promise.race([r(),pe(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),pe(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,i=document.documentElement,n=Math.max(r.scrollHeight,r.offsetHeight,i.clientHeight,i.scrollHeight,i.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,i.clientWidth,i.scrollWidth,i.offsetWidth);return{height:n,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await pe(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 At("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,$h.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var qu,ks,zu=I(()=>{"use strict";W();qu=P("cookies-utils"),ks=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 qu.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw qu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw qu.error("failed to remove cookie",{err:t}),t}}}});var Ku,ra,Wh=I(()=>{"use strict";Ku=R(require("p-retry")),ra=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(),i=()=>Promise.all([r,this.driver.takeScreenshot()]),[n,o]=await(0,Ku.default)(i,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:n}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,i=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),n=()=>Promise.all([i,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,Ku.default)(n,{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 Vh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let i=t.match(/^data:[^;]*;base64,(.*)$/);if(!i)throw new Error("Image is not in base64 format");let n=s.offset||{top:0,left:0};if(n.top*=r,n.left*=r,!s.elementRect)return TE.warn("missing elementRect",Hh.omit(s,"image")),{};let{elementRect:o}=s,a=await sa.Jimp.fromBuffer(Buffer.from(i[1],"base64")),c=o.left*r+n.left*r,l=o.top*r+n.top*r,d=o.width*r,m=o.height*r;c<0&&(d+=c,d=Math.max(d,0),c=0),l<0&&(m+=l,m=Math.max(m,0),l=0);let u=a.bitmap.width,f=a.bitmap.height;if(c+d>u&&(d=u-c),l+m>f&&(m=f-l),m<=0||d<=0)throw new Ju("height or width is equal or lower than zero");return{elementImage:await a.crop({x:c,y:l,w:d,h:m}).getBase64(qh)}}async function wE(s,e){let t=new sa.Jimp({width:s.width,height:s.height});for(let i of e){let n=i.image.match(/^data:[^;]*;base64,(.*)$/),o=await sa.Jimp.fromBuffer(Buffer.from(n[1],"base64"));t.composite(o,i.position.left,i.position.top)}return await t.getBase64(qh)}function vE(s,e){return wE(s,e)}async function SE(){}async function EE(s){function e(n){let o=s[n];return typeof o=="string"&&o.startsWith("data")}async function t(n){let o=await SE(s[n]);return{key:n,url:o}}let r=await ie(Object.keys(s).filter(e),t),i=Object.fromEntries(r.map(n=>[n.key,n.url]));return Object.assign(s,i)}function Gh(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 Hh,sa,TE,qh,Ju,ia,zh=I(()=>{"use strict";Hh=R(require("lodash"));F();sa=require("jimp");W();TE=P("image-capture-utils"),qh="image/png",Ju=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};ia=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 Vh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Gh(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 EE({screenImage:t.image,absoluteScreenHighlight:Gh(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,i=()=>pe(250),n=Boolean(e);async function o(u,f){n?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await i();let h=await r.takeScreenshot(),g=await Vh({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),v=f.height,b=Array.from({length:Math.ceil(h/g)},(w,E)=>({scrollX:Math.min(E*g,h-g),cropX:E*g-Math.min(E*g,h-g),cropW:g-(E*g-Math.min(E*g,h-g))})),T=Array.from({length:Math.ceil(y/v)},(w,E)=>({scrollY:Math.min(E*v,y-v),cropY:E*v-Math.min(E*v,y-v),cropH:v-(E*v-Math.min(E*v,y-v))}));return b.flatMap(w=>T.map(E=>({scrollPos:{x:w.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:w.cropX,width:w.cropW,height:E.cropH}})))}async function l(u,f){let h=await t.getCurrentScrollPosition(),g=c(u,f),y=await a(g);return await t.scrollToPosition(h),vE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(d,m)}}});var Kh,Jh,na,oa,Yh=I(()=>{"use strict";Kh=R(require("p-retry")),Jh=R(require("semver"));F();W();Hu();Wh();zh();ve();na=P("tab-service"),oa=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 i=this.getTabInfo(e,r);return`tabId=${r}, url=${i.url}, order=${i.order}, isMain=${i.isMain}, openerStepId=${i.openerStepId}, isClosed=${i.isClosed}, currentUrl: ${i.currentUrl}, lastUpdatedUrl: ${i.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,i){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),na.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,i)}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,i,n={}){let o=await this.getTabDetails(t,e,n),a=se();function c(l){return n.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:i},a}async addTab(e,t,r,i,n={}){let o=await this.buildTabInfo(e,t,r,i,n),a=new Ps(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new ia(t,a,new ra(t,this.driver,{takeScreenshots:n.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),i=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(i.length===1)return this._utils[i[0].infoId];let n=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return n.length>0?this._utils[n[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let i=r.filter(n=>n===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&i.length===1)}singleExactMatchForParts(e,t,r,i){let{urlUtils:n}=ee(),o=n.urlBreaker(e.url||e.currentUrl),a=n.urlBreaker(t.url||t.currentUrl),c=i(o),l=i(a),d=r.map(m=>n.urlBreaker(m)).map(m=>i(m)).filter(m=>m===c);return c===l&&d.length===1}isSameTab(e,t,r){let{tabMatcher:i}=ee();if(i){let l=this.getAllTabInfos(e),d=Object.keys(l).map(m=>l[m]);return i.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let n=this.getAllTabInfos(e),o=Object.keys(n).map(l=>n[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 i=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[i.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 i=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof i=="number"&&i>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 i=Promise.resolve("unknown");r.checkForMainTab&&(i=this.driver.executeJS("return window.__isMainTestimTab").then(n=>n.value));try{let[n,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),i]);return{title:n,url:o,isMainTab:a}}catch(n){na.error("failed to get url or title",{err:n})}}catch(i){na.error("failed to switch to tab",{tabId:e,err:i})}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 pe(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]){na.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let n=await this.waitForTabToOpen(e);await this.addNewTab(e,n,this.pendingTabs[e]),this.addFrameHandler(n),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,Kh.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=Jh.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,i=r&&e.parameterValues.some(n=>n.type==="locate"&&!n.frameLocators);return t&&(!r||i)}async getTabIdByTabInfo(e,t){var c,l;let{tabMatcher:r,commonConstants:i}=ee();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:i.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 n=(l=t.tabInfo)==null?void 0:l.openerStepId;await this.waitToPendingTabs(e,n),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 Yu,aa,Xu=I(()=>{"use strict";Yu=class{select(){return console.log(`
212
+ `,u=[],f=new ih.Worker(m,{eval:!0});try{return await le(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,v={...y,tstConsoleLogs:u};ft.debug("Run code worker response",{messageWithLogs:v,transactionId:s}),h(v)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?ft.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):ft.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",()=>{ft.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),n)}catch(h){if(!(h instanceof ce))throw h;return ft.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 qS(s){try{await th.promises.rm(s,{recursive:!0,force:!0})}catch(e){ft.warn("failed to remove install npm packages folder",{err:e})}}function nh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function vs(s,e,t,r,i,n){let o=nh(i,e,s,t),{data:a}=await zS(o,r,n);return a}async function Ss(s,e,t,r,i,n,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 v=qm(y.testimPackageLocalLocation);return[y.paramName,ws.join(y.testimPackageLocalLocation,v)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=nh(o,i,e,n);if(l){let y=await _i(l);y&&(c=y)}Buffer.isBuffer(c)&&(ft.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let f="data:,";return c==="data:"&&(ft.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=f),{...await HS(u,t,r,s,m,a,c),nodeVersion:process.version}}async function zS(s,e,t){let r=e.map(l=>`${l.packageName}@${l.packageVersion}`),i=oh(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?i:ws.join(i,`/${s}`),a=global.proxyUri;async function c(){let l="";try{if(l=await tl(o,r,a,t),ft.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=Gm(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ws.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw ft.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await le(c(),t)}catch(l){throw l instanceof ce&&ft.warn("timeout to install package",{packages:r,transactionId:s,err:l,timeout:t}),l}}function oh(){return ws.join(rh.tmpdir(),"/testim_local_packages")}function KS(){let s=oh();return qS(s)}var th,rh,ws,sh,ih,ft,Es=I(()=>{"use strict";th=R(require("fs")),rh=R(require("os")),ws=R(require("path"));F();is();sh=R(require("data-uri-to-buffer")),ih=require("worker_threads");Y();W();ge();is();de();ft=P("cli-service");KS().catch(s=>ft.warn("failed to clean local package folder",{err:s}))});var cr={};z(cr,{run:()=>XS});function JS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),i=JSON.stringify(s).length>r;return t?i:!1}catch{return!1}}var XS,ah=I(()=>{"use strict";Es();Y();de();XS=async(s,e,t)=>{let{code:r,stepId:i,incomingParams:n,context:o,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await Ss(r,i,n,o,a,c,l,d,m,u);return f&&JS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ce?new Error("Timeout while running action"):f}}});var vu={};z(vu,{run:()=>YS});var YS,ch=I(()=>{"use strict";Es();Y();YS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:i,stepResultId:n,packageData:o,timeout:a}=e.data;try{return{data:await vs(t,r,i,o,n,a),success:!0}}catch(c){if(c instanceof Pt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof ce)return{success:!1,code:"timeout"};throw c}}});async function uh(s,e,t,r){try{return await Su(s,e,t,r)}catch{jo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function ZS(s,e,t,r,i){return jo.info("finished to run remote step",{stepId:t,sessionId:i}),await uh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function lh(s,e,t,r,i){return jo.info("failed to run remote step",{stepId:t,sessionId:i,failureReason:r}),await uh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function ph(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:i,projectData:n}=s,o=t.type,a=e.getSessionId(),c=t.id;jo.info("start play remote step",{stepType:o,stepId:c,sessionId:a});let l=QS[o];if(!l)return await lh(i,r,c,`Failed to find step type ${o}`,a);try{let d=await l.run(e,t,n);return await ZS(i,r,c,d,a)}catch(d){return await lh(i,r,c,d.message,a)}}var jo,QS,dh=I(()=>{"use strict";ah();ge();ch();W();jo=P("step-playback"),QS={"cli-validation-code-step":cr,"cli-wait-for-code-step":cr,"cli-action-code-step":cr,"cli-api-code-step":cr,"cli-condition-step":cr,"cli-download-code-step":cr,"node-package":vu}});var fh={};z(fh,{preloadTests:()=>Gi});async function Gi(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await Ot(async()=>{let t=await ie(s.testId,r=>Hi({...e,testId:r}),{concurrency:2});return mh.keyBy(t,"testData.id")},"loadTests",tE,[e,s.testId])()}var mh,tE,$o=I(()=>{"use strict";mh=R(require("lodash"));er();ge();F();tE=1e3*60*60*10});var Eu,gh,Lr,rE,Iu,vt,Wo=I(()=>{"use strict";F();ut();Eu=R(require("ws")),gh=require("events");W();ae();Lr=P("socket-service"),rE=5e3,Iu=class extends gh.EventEmitter{constructor(){super(...arguments);this.clientId=se();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Lr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),rE)}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){Lr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(kd);return _t().then(i=>new Promise(n=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Eu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${i}`,o),this.ws.on("open",()=>{var a;return Lr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),n()}),this.ws.on("close",a=>{Lr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Eu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Lr.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){Lr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Lr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,i){let n=o=>{r(o)&&(i(o),this.removeListener(t,n))};this.on(t,n)}listenTo(t,r,i,n){function o(c){i(c)&&n(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,i,n=!1){return new Promise(o=>{let a=se(),c={query:r,id:a,type:i,fullDocument:n};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(i=>{let n=this.listeners[`${t}:${i}`];n&&(delete this.listeners[`${t}:${i}`],n.forEach(o=>this.removeListener(i,o)))})}removeFilter(t,r){let i=this.filterMap[t];if(!i)return;let n=Array.isArray(r)?r:[r];this.removeListeners(t,n),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:i})}},vt=new Iu});var yh,Ru,sE,iE,nE,hh,Vo,Is,xu=I(()=>{"use strict";yh=R(require("p-retry")),Ru=R(require("socket.io-client"));ae();F();W();sE=50,iE=10,nE=5e3,hh=10*1e3,Vo=P("base socket service"),Is=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Vo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var i;let r=this.rooms[t];(i=this.emitJoinRoom)==null||i.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let i="websocket";try{i=this._socket.io.engine.transport.name}catch{}Vo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${i}. 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===iE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=sE)throw new Error(`Can't connect to Testim Servers.
213
+ Action required: Please allow opening a websockets connection to ${he()} 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",()=>{Vo.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:hh,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(i=>{this.url=`${he()}/${t}`,this._socket=Ru.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",i),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:hh,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=`${he()}/${t}`,this._socket=Ru.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},i=()=>new Promise((n,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?n():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,yh.default)(()=>le(i(),nE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Vo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var bh={};z(bh,{remoteStepServiceSocketIO:()=>oE});var Au,oE,Th=I(()=>{"use strict";xu();Au=class extends Is{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]=i=>{i.resultId===t&&i.remoteStep&&i.remoteStep.status==="pending"&&r(i.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 Au});var wh={};z(wh,{remoteStepService:()=>Rs});var Cu,qi,Pu,Rs,Go=I(()=>{"use strict";Wo();oe();de();({REMOTE_STEP_SAVED:Cu}=kt),Pu=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(qi=(await Promise.resolve().then(()=>(Th(),bh))).remoteStepServiceSocketIO,qi.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:remoteStep`,{resultId:e},[Cu]):qi.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:remoteStep`,[Cu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}qi.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(vt.removeFilter(`${e}:remoteStep`,[Cu]),Promise.resolve()):qi.unlistenToRemoteStep(e)}},Rs=new Pu});var ku,Dr,vh=I(()=>{"use strict";xu();ku=class extends Is{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,i){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.testId===r&&i(n.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}},Dr=new ku});var Eh={};z(Eh,{testResultService:()=>Nt});var Sh,Ou,Nt,Ho=I(()=>{"use strict";Sh=require("events");Wo();oe();de();vh();Ou=class extends Sh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){vt.onConnect=()=>this.emit("socket-connected");return}Dr.init(e),Dr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[kt.TEST_RESULT_UPDATED,kt.TEST_RESULT_CREATED]):Dr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){vt.removeFilter(`${e}:testResult`,[kt.TEST_RESULT_UPDATED,kt.TEST_RESULT_CREATED]);return}await Dr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:testResult`,[kt.TEST_RESULT_UPDATED,kt.TEST_RESULT_CREATED],i=>i.resultId===e&&i.testId===t,i=>r(i));return}Dr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Dr.getSocket()}},Nt=new Ou});var Rh,xh,Ah,Ie,aE,Ch,Ih,cE,qo,Ph=I(()=>{"use strict";Rh=R(require("lodash"));F();ae();We();cs();ut();ge();dh();xh=R(require("p-retry")),Ah=require("node:url");W();$o();gs();oe();Go();Ho();ge();Ie=P("test-run-handler"),aE=3,Ch=20*1e3,Ih=s=>JSON.stringify(s).length<Ch,cE="Test couldn't be started",qo=class{constructor(e,t,r,i,n,o){this._executionId=e;this._executionName=t;this._options=i;this._branch=n;this._testRunStatus=o;this.seleniumPerfStats=new Cr;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=i.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=i.retries,this._remoteRunId=i.remoteRunId,this._customCapabilities=i.customCapabilities||((l=r.customCapabilities)==null?void 0:l.capabilities);let a=!((d=r.runConfig)!=null&&d.isMobileWeb)&&i.browser;this._runConfig=a?si(i.browser,i.saucelabs,i.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,i;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:(i=this._nativeApp)==null?void 0:i.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 i,n,o,a;return this.isAppFromDevice?null:r?(n=(i=r.gridData)==null?void 0:i[e])==null?void 0:n[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 ri(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Xr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Nn.FROM_DEVICE:Nn.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${he()}/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 Hi({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,i;let t={tokenV3:await _t(),refreshToken:ro(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Fd(),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 so()};if(this._options.disableMockNetwork&&dt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let n=this.runData,o=Ih(n);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(n).length,c=this.testId;o?(Object.assign(t,{runData:n}),Ie.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Ie.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Ch} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((i=this._options.lightweightMode)!=null&&i.preloadTests&&this._options.useChromeLauncher){let n=await Gi(this._options);Object.assign(t,{preloadedTest:n[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Ie.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 n;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((n=this._options.lightweightMode)!=null&&n.disableResults&&!t&&Ih(e))return;let r=async()=>{try{return await Du(this._options.project,this._testId,this._testResultId,e)}catch(o){return Ie.error("failed to upload run data artifact (runner)",{err:o}),""}},i=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Lu(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=i(),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===cE||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:i}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:n}=t.find(o=>o.type==="page")||{};if(!i)throw new Error("Tricentis Testim extension not found");if(!n)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:i,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 Ie.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 Ah.URL(e)}catch{return}let{username:i,password:n}=r;if(i||n)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,i=n=>{if(!r){if(this.isRetryKeyMismatch(n)){Ie.warn(`ignoring result update for on started due to retry key mismatch, got ${n.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(n.status)&&(n.resultId=this.testResultId,n.status==="completed"&&!this.isRerunOnInfraError(n.reason)&&(Ie.info("setting _wasCompletedOnStartedCheck to true",{testResult:n,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=n),r=!0,t(n))}};if(this._options.disableSockets){let n=Date.now()+e,o=async()=>{if(Date.now()>n)return;let{testId:a,testResultId:c,branch:l,_options:{project:d}}=this;try{let m=await Nr(a,c,d,l);i(m),r||setTimeout(o,3e3)}catch(m){Ie.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else Nt.listenToTestResult(this._testResultId,this._testId,i)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:i}=this;try{let n=await Nr(e,t,r,i),o=["running","completed"];if(o.includes(n.status))return Ie.info(`get status: ${n.status} after not get test started status`,{testId:e,testResultId:t,branch:i}),n;throw Ie.error(`test not start test status: ${n.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:i}),new Error(Pe.TEST_START_TIMEOUT_MSG)}catch(n){throw Ie.error("failed to get test result after test start timeout",{err:n,testId:e,testResultId:t,branch:i}),new Error(Pe.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Nt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Ie.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Nt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Ie.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 i=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),n=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Rh.debounce(async()=>{try{await Nt.joinToTestResult(this._testResultId,this.testId)}catch(o){Ie.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Nr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Ie.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"?(Ie.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 Ie.warn("Error while trying to check status on socket connect",o),!1}},i,{maxWait:n}),!this._options.disableSockets)Nt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await _u(this._testResultId,this._options.project,this.retryKey);a?await e()||(Ie.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Ie.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Nt.off("socket-connected",e)}}listenToRemoteStep(e){Rs.listenToRemoteStep(this.testResultId,t=>{ph(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:aE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var zo,kh=I(()=>{"use strict";Ph();zo=class{constructor(e,t,r,i,n,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));!i.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),i.appId&&this.pendingAppUploads.set(i.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new qo(e,t,c,i,n,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function _h(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(i=>({testId:i,testConfig:{},resultId:se()}))]}:await Fu({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 Nu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,i)=>r+(s[i].success===!0?1:0),0);return e===t}async function Mu(s,e){let t=s.mode===K.EXTENSION?Mr:zi,r=Oh.difference(ei(s,e),t);if(r.length>0)throw dt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new x(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Oh,Mr,zi,Ko=I(()=>{"use strict";Oh=R(require("lodash"));F();cs();ge();Y();oe();Mr=["edge-chromium","chrome"],zi=[...Mr,"firefox","safari","safari technology preview"]});var lE,uE,pE,Ki,Uu=I(()=>{"use strict";os();ds();W();lE=P("worker-utils"),uE=async(s,e,t)=>{e&&await Tl(s,t)},pE=async(s,e,t)=>{await Hl(s,e,t)},Ki=async(s,e,t,r,i,n)=>{lE.info("releasing player",{hasPlayer:Boolean(n)});try{await(n==null?void 0:n.onDone())}finally{i==="mongo"&&await uE(s,e,t),i==="redis"&&await pE(s,r,t)}}});function gE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Yo,Nh,Qo,Zo,Mh,St,Lh,Dh,Jo,Bu,Fr,dE,ju,mE,qt,fE,Xo,hE,Mt,Ji=I(()=>{"use strict";Yo=R(require("ms")),Nh=R(require("lodash")),Qo=R(require("p-retry")),Zo=R(require("dayjs")),Mh=R(require("dayjs/plugin/duration"));F();We();os();ds();ge();W();Uu();Dt();_o();de();Go();Ho();ut();He();oe();Y();Zo.default.extend(Mh.default);St=P("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Lh,TEST_START_TIMEOUT_MSG:Dh,TEST_COMPLETE_TIMEOUT_MSG:Jo,TEST_REACHED_CUSTOM_TIMEOUT_MSG:Bu}=Pe,{SETUP_TIMEOUT:Fr,NETWORK_ERROR:dE,GRID_ERROR:ju,BROWSER_CLOSED:mE,SELENIUM_ERROR:qt,UNKNOWN_ERROR:fE,MOBILE_SESSION_ERROR:Xo}=Kr;hE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Mt=class{constructor(e,t,r,i,n,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=i;this.onTestStarted=n;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new ne;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await Sf(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,i){throw new zs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),St.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!Qe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:fe.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var i,n;if(((i=this.options.gridData)==null?void 0:i.mode)==="local")return;let t=Yr(O,(n=this.options.gridData)==null?void 0:n.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:fe.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=wr(O.flags.appiumConnectionRequestTimeout.getValue(),(0,Yo.default)("2m")),i=wr(O.flags.appiumConnectionRetryCount.getValue(),1),n=r*i;return e===N.BROWSERSTACK||t&&e===N.TESTIM_TDC?n+(0,Yo.default)("10m"):n+(0,Yo.default)("1m")}getSessionTimeout(){if(Zt(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,Qo.default)(async()=>{let i=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Pe.GET_BROWSER_TIMEOUT_MSG)}catch(n){return t++,await this.handleGetSlotError(n,i)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Qo.default)(async()=>{var i,n;let r=Date.now();try{let o=(i=this.options.company)==null?void 0:i.companyId,a=(n=this.options.projectData)==null?void 0:n.projectId;return await le(Kf(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 Yt?St.info("could not get grid slot due to concurrency issue",r):St.error("error getting grid slot",{error:e,...r}),await pe(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 n;let r=(n=this.userData)==null?void 0:n.projectId,i;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;i=await(0,Qo.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await Ef(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===K.APPIUM?"device":"browser";throw St.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,r,++l),m.onDone(),!(u instanceof Ct)&&this.options.mode!==K.APPIUM&&await pe(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:c-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(o){throw await Ki(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,i),[Ct,Hr].some(a=>o instanceof a)?o:o instanceof nt?new br(o,ju):new br(o,qt)}return i}async runTest(e,t,r){var d;M("inside runTest");let i=(d=this.userData)==null?void 0:d.projectId,n=this.handleQuarantine(e);if(n)return n;let o=Zt(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 _t(),await this.runTestOnce(e,l)}finally{await Ki(this.id,this.releaseSlotOnTestFinished,i,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let i=async(g,y)=>{var D,j;if(Qe(g,this.options)||Yr(O,(D=this.options.gridData)==null?void 0:D.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let v=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let b=H=>y==null?void 0:y.message.includes(H),T=y&&y instanceof br,w=b(Dh),E=y&&(b(Jo)||b(Bu)||w&&!e.retryOnInfraErrors),A=!!b(Bu)&&!!this.testRunTimeout,B=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||w)&&e.retryOnInfraErrors,V=E&&e.hasMoreTimeoutRetries()&&!A,S=e.hasMoreRetries()&&!T&&!E,C=!g.success&&(S||V||B);try{let H=e.retryKey;g.testRetryKey=H;let G=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,v,C,G),await this.runTestCleanup(),C){if(V&&await e.startNewTimeoutRetry(),B){St.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 J=(j=this.options.projectData)==null?void 0:j.projectId,xe=e.testResultId,Te=e.testId;await ea(J,xe,Te,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return S&&!B&&!V&&await e.startNewRetry(),St.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:H,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(C)}t(this.id,...r);return}catch(H){if(H instanceof Xt)return;St.error("failed to process test result",{error:H}),t(this.id,...r);return}},n=()=>`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. ${Lc()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:v,APP_NEVER_STARTED:b,TIMEOUT_ERROR:T,SAUCELABS_APP_IS_NOT_INSTALLED:w}=$c,E=g instanceof Error?g.message:g;if(E.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),E.includes(Lh)||E.includes(T))return{errorType:Fr,reason:"timeout while getting device"};if(E.includes(Jo)||E.includes(Bu)){if(!this.testRunTimeout)return{errorType:Fr,reason:"Test timeout reached!"};let A=Zo.default.duration({milliseconds:this.testRunTimeout});return{errorType:Fr,reason:`Test timeout reached (timeout: ${Un(A)})`}}return E.includes(v)||E.includes(w)?{errorType:Xo,reason:"app doesn't exist on device"}:E.includes(b)?{errorType:Xo,reason:"app never started, check app permission or app activity"}:E.includes(y)?{errorType:Xo,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Xo,reason:E}},a=(g,y)=>{let v=this.options.mode===K.APPIUM?"device":"browser";if(!y&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:dE,reason:n()};let b=g instanceof Error?g.message:g;if(b.includes(Lh))return{errorType:Fr,reason:`Test couldn't get ${v}`};if(b.includes(Dh))return{errorType:Fr,reason:"Test couldn't be started"};if(g instanceof br&&g.type){if(g.type===ju)return{errorType:ju,reason:`Test couldn't get ${v} from grid - ${g.message}`};if(g.type===qt)return{errorType:qt,reason:`Failed to create new session - ${g.message}`}}return b.includes(Jo)?this.testRunTimeout?{errorType:Fr,reason:`Test timeout reached (timeout: ${Un(Zo.default.duration({milliseconds:this.testRunTimeout}))})`}:{errorType:Fr,reason:"Test timeout reached: test is too long"}:"type"in g&&g.type===mE?{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 ${v} you requested is supported in your plan`}:{errorType:fE,reason:b}},c=async g=>{var w;let y=await _c();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(n()),St.warn("error on run",{err:g});let v=(w=this.userData)==null?void 0:w.projectId,{errorType:b,reason:T}=this.options.mode===K.APPIUM?o(g):a(g,y);ea(v,this.testResultId,this.testId,{status:Qs.COMPLETED,success:!1,reason:T,errorType:b,testRetryKey:e.retryKey,setupStepResult:{status:Qs.COMPLETED,success:!1,reason:T,errorType:b}},e.remoteRunId),await i(gE(this.testId,this.testName,this.testResultId,T),g)},l=async g=>{var w;let y=this.testId,v=this.testResultId,b=(w=this.userData)==null?void 0:w.projectId,T=this.branch;if(!y||!v||!b||!T)return St.warn("Test failed. Not enough data to recover results via API",{err:g}),c(g);try{let E=await Nr(y,v,b,T);if(St.warn("Test failed. Got results via API",{err:g,testResult:Nh.default.omit(E,hE),resultId:v}),E&&E.status===Qs.COMPLETED&&!g.message.includes(Jo))return await i(E);throw g}catch(E){return E!==g&&St.error("Failed to fetch test results from server",{testId:y,resultId:v,projectId:b,branch:T,err:E}),c(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===K.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&Rs.joinToRemoteStep(this.testResultId),!d&&Nt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==K.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await i(y),M("After onRunComplete"),t(this.id,...r)}catch(y){await l(y),t(this.id,...r)}finally{m||Rs.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 Uh,Fh,xs,$u=I(()=>{"use strict";F();Uh=R(require("p-retry"));F();W();Y();Fh=P("window-utils"),xs=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(n,o){let a=document.elementFromPoint(n,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:i}=await this.driver.executeJS(r,e,t);return i}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(i=3)=>{try{await this.driver.url(e)}catch(n){let o=n.message.includes("method IWebBrowser2::Navigate2() failed");if(n.seleniumStack&&o&&i>0)return Fh.warn("selenium navigation failed. retrying to navigate",{err:n}),await pe(1500),r(i-1);throw!n.seleniumStack&&o&&Fh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:n}),n}};return Promise.race([r(),pe(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),pe(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,i=document.documentElement,n=Math.max(r.scrollHeight,r.offsetHeight,i.clientHeight,i.scrollHeight,i.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,i.clientWidth,i.scrollWidth,i.offsetWidth);return{height:n,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await pe(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 Ct("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Uh.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var Wu,As,Vu=I(()=>{"use strict";W();Wu=P("cookies-utils"),As=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 Wu.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw Wu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw Wu.error("failed to remove cookie",{err:t}),t}}}});var Gu,ta,Bh=I(()=>{"use strict";Gu=R(require("p-retry")),ta=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(),i=()=>Promise.all([r,this.driver.takeScreenshot()]),[n,o]=await(0,Gu.default)(i,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:n}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,i=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),n=()=>Promise.all([i,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,Gu.default)(n,{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 jh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let i=t.match(/^data:[^;]*;base64,(.*)$/);if(!i)throw new Error("Image is not in base64 format");let n=s.offset||{top:0,left:0};if(n.top*=r,n.left*=r,!s.elementRect)return yE.warn("missing elementRect",Wh.omit(s,"image")),{};let{elementRect:o}=s,a=await ra.Jimp.fromBuffer(Buffer.from(i[1],"base64")),c=o.left*r+n.left*r,l=o.top*r+n.top*r,d=o.width*r,m=o.height*r;c<0&&(d+=c,d=Math.max(d,0),c=0),l<0&&(m+=l,m=Math.max(m,0),l=0);let u=a.bitmap.width,f=a.bitmap.height;if(c+d>u&&(d=u-c),l+m>f&&(m=f-l),m<=0||d<=0)throw new Hu("height or width is equal or lower than zero");return{elementImage:await a.crop({x:c,y:l,w:d,h:m}).getBase64(Vh)}}async function bE(s,e){let t=new ra.Jimp({width:s.width,height:s.height});for(let i of e){let n=i.image.match(/^data:[^;]*;base64,(.*)$/),o=await ra.Jimp.fromBuffer(Buffer.from(n[1],"base64"));t.composite(o,i.position.left,i.position.top)}return await t.getBase64(Vh)}function TE(s,e){return bE(s,e)}async function wE(){}async function vE(s){function e(n){let o=s[n];return typeof o=="string"&&o.startsWith("data")}async function t(n){let o=await wE(s[n]);return{key:n,url:o}}let r=await ie(Object.keys(s).filter(e),t),i=Object.fromEntries(r.map(n=>[n.key,n.url]));return Object.assign(s,i)}function $h(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 Wh,ra,yE,Vh,Hu,sa,Gh=I(()=>{"use strict";Wh=R(require("lodash"));F();ra=require("jimp");W();yE=P("image-capture-utils"),Vh="image/png",Hu=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};sa=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 jh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:$h(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 vE({screenImage:t.image,absoluteScreenHighlight:$h(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,i=()=>pe(250),n=Boolean(e);async function o(u,f){n?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await i();let h=await r.takeScreenshot(),g=await jh({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),v=f.height,b=Array.from({length:Math.ceil(h/g)},(w,E)=>({scrollX:Math.min(E*g,h-g),cropX:E*g-Math.min(E*g,h-g),cropW:g-(E*g-Math.min(E*g,h-g))})),T=Array.from({length:Math.ceil(y/v)},(w,E)=>({scrollY:Math.min(E*v,y-v),cropY:E*v-Math.min(E*v,y-v),cropH:v-(E*v-Math.min(E*v,y-v))}));return b.flatMap(w=>T.map(E=>({scrollPos:{x:w.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:w.cropX,width:w.cropW,height:E.cropH}})))}async function l(u,f){let h=await t.getCurrentScrollPosition(),g=c(u,f),y=await a(g);return await t.scrollToPosition(h),TE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(d,m)}}});var Hh,qh,ia,na,zh=I(()=>{"use strict";Hh=R(require("p-retry")),qh=R(require("semver"));F();W();$u();Bh();Gh();ve();ia=P("tab-service"),na=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 i=this.getTabInfo(e,r);return`tabId=${r}, url=${i.url}, order=${i.order}, isMain=${i.isMain}, openerStepId=${i.openerStepId}, isClosed=${i.isClosed}, currentUrl: ${i.currentUrl}, lastUpdatedUrl: ${i.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,i){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),ia.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,i)}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,i,n={}){let o=await this.getTabDetails(t,e,n),a=se();function c(l){return n.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:i},a}async addTab(e,t,r,i,n={}){let o=await this.buildTabInfo(e,t,r,i,n),a=new xs(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new sa(t,a,new ta(t,this.driver,{takeScreenshots:n.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),i=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(i.length===1)return this._utils[i[0].infoId];let n=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return n.length>0?this._utils[n[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let i=r.filter(n=>n===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&i.length===1)}singleExactMatchForParts(e,t,r,i){let{urlUtils:n}=ee(),o=n.urlBreaker(e.url||e.currentUrl),a=n.urlBreaker(t.url||t.currentUrl),c=i(o),l=i(a),d=r.map(m=>n.urlBreaker(m)).map(m=>i(m)).filter(m=>m===c);return c===l&&d.length===1}isSameTab(e,t,r){let{tabMatcher:i}=ee();if(i){let l=this.getAllTabInfos(e),d=Object.keys(l).map(m=>l[m]);return i.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let n=this.getAllTabInfos(e),o=Object.keys(n).map(l=>n[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 i=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[i.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 i=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof i=="number"&&i>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 i=Promise.resolve("unknown");r.checkForMainTab&&(i=this.driver.executeJS("return window.__isMainTestimTab").then(n=>n.value));try{let[n,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),i]);return{title:n,url:o,isMainTab:a}}catch(n){ia.error("failed to get url or title",{err:n})}}catch(i){ia.error("failed to switch to tab",{tabId:e,err:i})}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 pe(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]){ia.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let n=await this.waitForTabToOpen(e);await this.addNewTab(e,n,this.pendingTabs[e]),this.addFrameHandler(n),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,Hh.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=qh.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,i=r&&e.parameterValues.some(n=>n.type==="locate"&&!n.frameLocators);return t&&(!r||i)}async getTabIdByTabInfo(e,t){var c,l;let{tabMatcher:r,commonConstants:i}=ee();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:i.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 n=(l=t.tabInfo)==null?void 0:l.openerStepId;await this.waitToPendingTabs(e,n),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 qu,oa,zu=I(()=>{"use strict";qu=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(){}},aa=new Yu});var Xi,ca,la=I(()=>{"use strict";zu();F();ve();Xi={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"},ca=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=ni;this.getLinksFromUnescapeHTML=oi;this.cookieUtils=new ks(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:i}=this.sessionPlayerInit,n=i.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-n.x,y:e.y-n.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:i}=await this.driver.executeJS(`return (function() { ${r} })();`);return i}}});function Qh(s){class e{constructor(r,i){this.frameManager=r;this.LocateElementPlayer=i;this._cache={}}cacheResults(r,i){this._cache[r]=i}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let i=Xh(r.seleniumFrameElement);i&&this.cacheResults(i,r.frameLocateResultUrl)}}async foundFrameCallback(r,i,n){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 IE.error(u),new Error(u)}let l=await s.switchToLocatedFrame(a),d=Xh(l.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:i.tabInfo,tabId:i.tabId,testimFrameId:n,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${n}`,seleniumFrameElement:l.value,frameLocateResultUrl:m}}async locate(r,i,n,o,a,c){let l=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${i}`;let d=await l.locate(r,n,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:n.frameOffset.top+h.top,left:n.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,i,n,o){let a=O.flags.enableFrameSwitchOptimization.isEnabled(),l=n.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=l&&l.stepId===r.id&&l.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=i.findIndex(v=>v.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let v=i.slice(y+1),b=0;for(let T of v)b++,this.currentFrameHandler=await this.locate(T,b,this.currentFrameHandler,n,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 i)h++,g=await this.locate(y,h,g,n,o,r);return g}}return e}var IE,RE,Xh,Zh=I(()=>{"use strict";W();de();ve();qr();IE=P("frame-locator"),RE="ELEMENT",Xh=s=>s?s[RE]||s[Kt]:null});var ua,Qu=I(()=>{"use strict";oe();ua=()=>{try{if(Od)return!1;if(require("inspector").url())return!0}catch{}return!1}});var q,me=I(()=>{"use strict";ve();q=class{constructor(e,t,r,i={},n=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=i;this.stepActionUtils=n;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 CE(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 AE(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 i=new ey.DOMParser().parseFromString("<html><body></body></html>","text/html");return i.body.outerHTML=e,Object.assign(i,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,i,n,o,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:d,positionUtils:m}=ee();if(CE(i,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(i.clickOffset,r)].filter(Boolean),g=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,i),y;try{y=await s.execute(`return ${g}`)}catch(E){throw Br.error("failed to execute getVisibilityCode",{err:E}),E}let{value:v}=y||{},b=v.elementVisibilityInfo||xE,[T,w]=v.elementsFromPointResults||[null,null];return d.checkElementVisibility(b,i,w,T,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=ee();await s.execute(r(t))}}}var ey,Br,xE,Qi,ty=I(()=>{"use strict";me();W();de();ve();ey=require("linkedom"),Br=P("locate-step-action"),xE={opacity:1,clientRects:{}};Qi=class extends q{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return AE(e)}static getFrameIdByTestimFrameId(){throw Br.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw Br.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw Br.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw Br.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw Br.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw Br.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var ry={};z(ry,{scroll:()=>PE});var PE,sy=I(()=>{"use strict";PE=function(s,e,t,r,i,n,o,a){function c(b,T){if(!T)return{success:!1};elementScrollTo(T,b.x,b.y);let w=T.scrollLeft,E=T.scrollTop;return{success:Math.abs(E-b.y)<1&&Math.abs(w-b.x)<1,actualX:w,actualY:E}}function l(b,T){if(!t)return{x:i,y:n};let w=getLocatedElement(T);if(r&&!w)return{x:b.scrollWidth,y:b.scrollHeight};if(!w)throw new Error("could not find target element");let E=w.getBoundingClientRect(),C=0,_=0,B=Math.max(window.innerHeight-(E.height+10),0),V=Math.max(window.innerWidth-(E.width+10),0);return C=a?b.scrollTop+E.top-Math.min(n,B):b.scrollTop,_=o?b.scrollLeft+E.left-Math.min(i,V):b.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,v=getLocatedElement(e);if(t&&r&&!v)return{success:!1,expectedPosition:f};if(t){if(!v)throw new Error("could not find target to scroll to");let b=v.getBoundingClientRect();g=b.left,y=b.top}return{success:h.success,actualX:g,actualY:y}}});var pa,iy=I(()=>{"use strict";me();pa=class extends q{getFailureString(e,t,r,i,n){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${n}, x: ${i})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${n}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${i}`),o}async scroll(e,t,r){let{codeSnippets:i,commonConstants:{stepResult:n}}=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(()=>(sy(),ry)),d=`
217
+ `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},oa=new qu});var Xi,aa,ca=I(()=>{"use strict";Vu();F();ve();Xi={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"},aa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=ii;this.getLinksFromUnescapeHTML=ni;this.cookieUtils=new As(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:i}=this.sessionPlayerInit,n=i.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-n.x,y:e.y-n.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:i}=await this.driver.executeJS(`return (function() { ${r} })();`);return i}}});function Jh(s){class e{constructor(r,i){this.frameManager=r;this.LocateElementPlayer=i;this._cache={}}cacheResults(r,i){this._cache[r]=i}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let i=Kh(r.seleniumFrameElement);i&&this.cacheResults(i,r.frameLocateResultUrl)}}async foundFrameCallback(r,i,n){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 SE.error(u),new Error(u)}let l=await s.switchToLocatedFrame(a),d=Kh(l.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:i.tabInfo,tabId:i.tabId,testimFrameId:n,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${n}`,seleniumFrameElement:l.value,frameLocateResultUrl:m}}async locate(r,i,n,o,a,c){let l=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${i}`;let d=await l.locate(r,n,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:n.frameOffset.top+h.top,left:n.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,i,n,o){let a=O.flags.enableFrameSwitchOptimization.isEnabled(),l=n.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=l&&l.stepId===r.id&&l.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=i.findIndex(v=>v.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let v=i.slice(y+1),b=0;for(let T of v)b++,this.currentFrameHandler=await this.locate(T,b,this.currentFrameHandler,n,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 i)h++,g=await this.locate(y,h,g,n,o,r);return g}}return e}var SE,EE,Kh,Xh=I(()=>{"use strict";W();de();ve();Vr();SE=P("frame-locator"),EE="ELEMENT",Kh=s=>s?s[EE]||s[Kt]:null});var la,Ku=I(()=>{"use strict";ae();la=()=>{try{if(Pd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var q,me=I(()=>{"use strict";ve();q=class{constructor(e,t,r,i={},n=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=i;this.stepActionUtils=n;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 RE(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 xE(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 i=new Yh.DOMParser().parseFromString("<html><body></body></html>","text/html");return i.body.outerHTML=e,Object.assign(i,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,i,n,o,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:d,positionUtils:m}=ee();if(RE(i,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(i.clickOffset,r)].filter(Boolean),g=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,i),y;try{y=await s.execute(`return ${g}`)}catch(E){throw Ur.error("failed to execute getVisibilityCode",{err:E}),E}let{value:v}=y||{},b=v.elementVisibilityInfo||IE,[T,w]=v.elementsFromPointResults||[null,null];return d.checkElementVisibility(b,i,w,T,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=ee();await s.execute(r(t))}}}var Yh,Ur,IE,Yi,Qh=I(()=>{"use strict";me();W();de();ve();Yh=require("linkedom"),Ur=P("locate-step-action"),IE={opacity:1,clientRects:{}};Yi=class extends q{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return xE(e)}static getFrameIdByTestimFrameId(){throw Ur.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw Ur.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw Ur.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw Ur.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw Ur.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw Ur.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Zh={};z(Zh,{scroll:()=>AE});var AE,ey=I(()=>{"use strict";AE=function(s,e,t,r,i,n,o,a){function c(b,T){if(!T)return{success:!1};elementScrollTo(T,b.x,b.y);let w=T.scrollLeft,E=T.scrollTop;return{success:Math.abs(E-b.y)<1&&Math.abs(w-b.x)<1,actualX:w,actualY:E}}function l(b,T){if(!t)return{x:i,y:n};let w=getLocatedElement(T);if(r&&!w)return{x:b.scrollWidth,y:b.scrollHeight};if(!w)throw new Error("could not find target element");let E=w.getBoundingClientRect(),A=0,_=0,B=Math.max(window.innerHeight-(E.height+10),0),V=Math.max(window.innerWidth-(E.width+10),0);return A=a?b.scrollTop+E.top-Math.min(n,B):b.scrollTop,_=o?b.scrollLeft+E.left-Math.min(i,V):b.scrollLeft,{x:Math.round(_),y:Math.round(A)}}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,v=getLocatedElement(e);if(t&&r&&!v)return{success:!1,expectedPosition:f};if(t){if(!v)throw new Error("could not find target to scroll to");let b=v.getBoundingClientRect();g=b.left,y=b.top}return{success:h.success,actualX:g,actualY:y}}});var ua,ty=I(()=>{"use strict";me();ua=class extends q{getFailureString(e,t,r,i,n){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${n}, x: ${i})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${n}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${i}`),o}async scroll(e,t,r){let{codeSnippets:i,commonConstants:{stepResult:n}}=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(()=>(ey(),Zh)),d=`
218
218
  const getLocatedElement = ${i.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:n.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:n.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:n.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 ny,oy=I(()=>{"use strict";ny=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)]}},i=getLocatedElement(s.fromLocatedElement),n=getLocatedElement(s.toLocatedElement);if(!i)throw new Error("from element not found");if(!n)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(i,"dragstart"),o(n,"drop"),o(i,"dragend")}});var ay,cy=I(()=>{"use strict";ay=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",i=typeof PointerEvent=="function",n={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(S){e({status:"done",result:S,success:!0})}function a(S){S||={},e({status:"failed",result:S,success:!1,keep:!0})}function c(S){return S!=null&&S.toLowerCase?(S=S.toLowerCase(),S==="text"?"text/plain":S==="url"?"text/uri-list":S):S}function l(){try{return new DataTransfer}catch{return{data:{},setData(A,N){n[c(A)]=N},getData(A){return n[c(A)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(S){let A=S;for(;A&&A!==document.documentElement;){if(A.draggable)return A;A=A.parentElement}return null}function h(S,A,N){let j=A.element,{dispatchDragEventsOnClosestDraggable:H}=N;if(d.includes(S.type)&&H){if(!j&&A.lastDraggedElement)return A.lastDraggedElement;let G=f(j);if(G)return A.lastDraggedElement=G,G}return j}function g(S,A,N){function j(Te,gr,k){return k>Te&&k<gr}let H=S.pointerPosition||{};if(A)return{x:H.originX||0,y:H.originY||0};let G=N.getBoundingClientRect(),J=H.originX&&j(G.left,G.left+G.width,H.originX)?H.originX:G.left+G.width/2,xe=H.originY&&j(G.top,G.top+G.height,H.originY)?H.originY:G.top+G.height/2;return{x:J,y:xe}}function y(S,A,N){let j=(A==null?void 0:A.modifiers)||{},H=g(S,N.isDrag,N.element),G=(A==null?void 0:A.button)||0,J=S.event;return m.includes(J)?b(J,j,H.x,H.y,G):u.includes(J)?w(J,j,H.x,H.y):T(J,j,H.x,H.y,G)}function v(S,A,N){return{screenX:0,screenY:0,clientX:A,clientY:N,ctrlKey:Boolean(S.ctrl),altKey:Boolean(S.alt),shiftKey:Boolean(S.shift),metaKey:Boolean(S.meta),bubbles:!0,cancelable:!0,composed:!0}}function b(S,A,N,j,H){if(i){let J=v(A,N,j);return J.pointerType="mouse",J.isPrimary=!0,new window.PointerEvent(S,J)}let G=document.createEvent("PointerEvent");return G.initPointerEvent(S,!0,!0,document.defaultView,1,0,0,N,j,Boolean(A.ctrl),Boolean(A.alt),Boolean(A.shift),Boolean(A.meta),H,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),G}function T(S,A,N,j,H){let G=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return G.initMouseEvent(S,!0,!0,document.defaultView,1,0,0,N,j,Boolean(A.ctrl),Boolean(A.alt),Boolean(A.shift),Boolean(A.meta),H,document.body?document.body.parentNode:document.documentElement),G}function w(S,A,N,j){if(S==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let J=document.createEvent("CustomEvent");return J.initCustomEvent(S,!0,!0,null),Object.assign(J,{dataTransfer:window.TSTA.dataTransfer}),J}let H=v(A,N,j),G=new window.DragEvent(S,H);return Object.defineProperties(G,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),G}function E(S,A,N){let j=h(S,A,N);j==null||j.dispatchEvent(S)}function C(S,A){function N(){return S.event==="click"&&A.isDrag&&!A.allEventsOnSameElement}return N()}function _(S,A,N){if(N){let j=Math.min(N.timeStamp-A.timeStamp,40);setTimeout(()=>{B(S)},j)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function B(S){let A,N=S.events[S.eventIndex],j=S.events[++S.eventIndex];try{S.element=getLocatedElement(N.locatedElement),A=y(N,s,S)}catch(H){return a(`exception in get event in drag step:${H.message}`)}if(C(N,S))return _(S,N,j);if(A)try{E(A,S,N)}catch(H){return a(`exception in executeEvent in drag step:${H.message}`)}else return a(`cannot execute event ${N.event}`);_(S,N,j)}let V={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(V)}catch(S){a(S)}},0)}});var ly={};z(ly,{doClick:()=>kE});var kE,uy=I(()=>{"use strict";kE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(T,w){var _;function E(B){function V(){return n(B).find(N=>[...N.classList||[]].includes("Select-control"))}function S(){let N=V();return N?N.querySelector("input"):null}let A=S();A==null||A.focus()}let C=(_=T.quirks)==null?void 0:_.isReactSelect;w.type==="mousedown"&&C&&E(T.element)}function i(T,w){var C;let E=(C=T.quirks)==null?void 0:C.isCKEditorFrame;w.type==="click"&&E&&document.body.focus()}function n(T){let w=[];for(;T!=null&&T.parentNode;)w.push(T),T=T.parentNode;return w}function o(T){let w={status:"done",result:T,success:!0,...b.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(w)}function a(T){T||="",e({status:"failed",result:T,success:!1})}function c(T){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),T.dispatchEvent(w)}function l(T){let w={},E=T.getBoundingClientRect(),C=E.left+E.width/2,_=E.top+E.height/2,S=f("mousemove",w,C,_,0);T.dispatchEvent(S)}function d(T,w){function E(S,A,N){return N>S&&N<A}let C=T.pointerPosition||{},_=w.getBoundingClientRect(),B=C.originX&&E(_.left,_.left+_.width,C.originX)?C.originX:_.left+_.width/2,V=C.originY&&E(_.top,_.top+_.height,C.originY)?C.originY:_.top+_.height/2;return{x:B,y:V}}function m(T,w,E){return{screenX:0,screenY:0,clientX:w,clientY:E,ctrlKey:Boolean(T.ctrl),altKey:Boolean(T.alt),shiftKey:Boolean(T.shift),metaKey:Boolean(T.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(T,w,E,C){if(!window.PointerEvent)return;let _=m(w,E,C);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(T,_)}function f(T,w,E,C,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(T,!0,!0,document.defaultView,1,0,0,E,C,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),_,document.body?document.body.parentNode:document.documentElement),B}function h(T,w){let E=["pointerup","pointerdown","pointermove"],C=w.modifiers||{},_=d(T,w.element),B=w.button||0,V=T.event;return E.includes(V)?u(V,C,_.x,_.y):f(V,C,_.x,_.y,B)}function g(){var w;let T=document.activeElement;for(;(w=T.shadowRoot)!=null&&w.activeElement;)T=T.shadowRoot.activeElement;return T}function y(T){T.events.map(w=>{try{return h(w,T)}catch{return}}).filter(Boolean).forEach(w=>{T.element.dispatchEvent(w),r(T,w),i(T,w)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let b={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!b.element){a("element not found");return}c(b.element),l(b.element);try{y(b);let T=g(),w=b.quirks,E=w==null?void 0:w.isReactSelect,C=w==null?void 0:w.isCKEditorFrame;!E&&!C&&dispatchFocus(s.elementToFocusLocatedElement,T),o()}catch(T){a(T.toString())}}});var py={};z(py,{doDragPath:()=>OE});var OE,dy=I(()=>{"use strict";OE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",i=40;window.__unloadNavigator=n,window.addEventListener("unload",window.__unloadNavigator);function n(T){e({status:"done",result:T,success:!0})}function o(T){T||="",e({status:"failed",result:T,success:!1})}function a(T){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),T.dispatchEvent(w)}function c(T){let w={},E=T.getBoundingClientRect(),C=E.left+E.width/2,_=E.top+E.height/2,S=u("mousemove",w,C,_,0);T.dispatchEvent(S)}function l(T,w){function E(S,A,N){return N>S&&N<A}let C=T.pointerPosition||{};if(b.isDrag)return{x:C.originX||0,y:C.originY||0};let _=w.getBoundingClientRect(),B=C.originX&&E(_.left,_.left+_.width,C.originX)?C.originX:_.left+_.width/2,V=C.originY&&E(_.top,_.top+_.height,C.originY)?C.originY:_.top+_.height/2;return{x:B,y:V}}function d(T,w,E){return{screenX:0,screenY:0,clientX:w,clientY:E,ctrlKey:Boolean(T.ctrl),altKey:Boolean(T.alt),shiftKey:Boolean(T.shift),metaKey:Boolean(T.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(T,w,E,C,_){if(r){let V=d(w,E,C);return V.pointerType="mouse",V.isPrimary=!0,new window.PointerEvent(T,V)}let B=document.createEvent("PointerEvent");return B.initPointerEvent(T,!0,!0,document.defaultView,1,0,0,E,C,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),B}function u(T,w,E,C,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(T,!0,!0,document.defaultView,1,0,0,E,C,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),_,document.body?document.body.parentNode:document.documentElement),B}function f(T,w){let E=["pointerup","pointerdown","pointermove"],C=w.modifiers||{},_=l(T,w.element),B=w.button||0,V=T.event;return E.includes(V)?m(V,C,_.x,_.y,B):u(V,C,_.x,_.y,B)}function h(T,w){function E(){return T.event==="click"&&w.isDrag&&!w.allEventsOnSameElement}return E()}function g(T,w,E){try{let C=f(w.events[T],w);h(C,w)||w.element.dispatchEvent(C)}catch{}if(T+1===w.events.length)E();else{let C=Math.min(w.events[T+1].timeStamp-w.events[T].timeStamp,i);setTimeout(()=>{g(T+1,w,E)},C)}}function y(T,w){g(0,T,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w()})}let b={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(!b.element){o("element not found");return}a(b.element),c(b.element),y(b,()=>{n()})}});var Zi,da,my=I(()=>{"use strict";Zi=R(require("lodash"));me();oy();de();cy();da=class extends q{getDnDRectsAndOffsets(e,t,r,i){let n=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(i,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:n.x,fromY:n.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),i=t.data.timeToPlayStep+3e3,n=e.events;if(!(n!=null&&n.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:n,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(uy(),ly)),Promise.resolve().then(()=>($i(),ji))]),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:n.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:n.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:n.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 ry,sy=I(()=>{"use strict";ry=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)]}},i=getLocatedElement(s.fromLocatedElement),n=getLocatedElement(s.toLocatedElement);if(!i)throw new Error("from element not found");if(!n)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(i,"dragstart"),o(n,"drop"),o(i,"dragend")}});var iy,ny=I(()=>{"use strict";iy=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",i=typeof PointerEvent=="function",n={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(S){e({status:"done",result:S,success:!0})}function a(S){S||={},e({status:"failed",result:S,success:!1,keep:!0})}function c(S){return S!=null&&S.toLowerCase?(S=S.toLowerCase(),S==="text"?"text/plain":S==="url"?"text/uri-list":S):S}function l(){try{return new DataTransfer}catch{return{data:{},setData(C,D){n[c(C)]=D},getData(C){return n[c(C)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(S){let C=S;for(;C&&C!==document.documentElement;){if(C.draggable)return C;C=C.parentElement}return null}function h(S,C,D){let j=C.element,{dispatchDragEventsOnClosestDraggable:H}=D;if(d.includes(S.type)&&H){if(!j&&C.lastDraggedElement)return C.lastDraggedElement;let G=f(j);if(G)return C.lastDraggedElement=G,G}return j}function g(S,C,D){function j(Te,fr,k){return k>Te&&k<fr}let H=S.pointerPosition||{};if(C)return{x:H.originX||0,y:H.originY||0};let G=D.getBoundingClientRect(),J=H.originX&&j(G.left,G.left+G.width,H.originX)?H.originX:G.left+G.width/2,xe=H.originY&&j(G.top,G.top+G.height,H.originY)?H.originY:G.top+G.height/2;return{x:J,y:xe}}function y(S,C,D){let j=(C==null?void 0:C.modifiers)||{},H=g(S,D.isDrag,D.element),G=(C==null?void 0:C.button)||0,J=S.event;return m.includes(J)?b(J,j,H.x,H.y,G):u.includes(J)?w(J,j,H.x,H.y):T(J,j,H.x,H.y,G)}function v(S,C,D){return{screenX:0,screenY:0,clientX:C,clientY:D,ctrlKey:Boolean(S.ctrl),altKey:Boolean(S.alt),shiftKey:Boolean(S.shift),metaKey:Boolean(S.meta),bubbles:!0,cancelable:!0,composed:!0}}function b(S,C,D,j,H){if(i){let J=v(C,D,j);return J.pointerType="mouse",J.isPrimary=!0,new window.PointerEvent(S,J)}let G=document.createEvent("PointerEvent");return G.initPointerEvent(S,!0,!0,document.defaultView,1,0,0,D,j,Boolean(C.ctrl),Boolean(C.alt),Boolean(C.shift),Boolean(C.meta),H,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),G}function T(S,C,D,j,H){let G=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return G.initMouseEvent(S,!0,!0,document.defaultView,1,0,0,D,j,Boolean(C.ctrl),Boolean(C.alt),Boolean(C.shift),Boolean(C.meta),H,document.body?document.body.parentNode:document.documentElement),G}function w(S,C,D,j){if(S==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let J=document.createEvent("CustomEvent");return J.initCustomEvent(S,!0,!0,null),Object.assign(J,{dataTransfer:window.TSTA.dataTransfer}),J}let H=v(C,D,j),G=new window.DragEvent(S,H);return Object.defineProperties(G,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),G}function E(S,C,D){let j=h(S,C,D);j==null||j.dispatchEvent(S)}function A(S,C){function D(){return S.event==="click"&&C.isDrag&&!C.allEventsOnSameElement}return D()}function _(S,C,D){if(D){let j=Math.min(D.timeStamp-C.timeStamp,40);setTimeout(()=>{B(S)},j)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function B(S){let C,D=S.events[S.eventIndex],j=S.events[++S.eventIndex];try{S.element=getLocatedElement(D.locatedElement),C=y(D,s,S)}catch(H){return a(`exception in get event in drag step:${H.message}`)}if(A(D,S))return _(S,D,j);if(C)try{E(C,S,D)}catch(H){return a(`exception in executeEvent in drag step:${H.message}`)}else return a(`cannot execute event ${D.event}`);_(S,D,j)}let V={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(V)}catch(S){a(S)}},0)}});var oy={};z(oy,{doClick:()=>CE});var CE,ay=I(()=>{"use strict";CE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(T,w){var _;function E(B){function V(){return n(B).find(D=>[...D.classList||[]].includes("Select-control"))}function S(){let D=V();return D?D.querySelector("input"):null}let C=S();C==null||C.focus()}let A=(_=T.quirks)==null?void 0:_.isReactSelect;w.type==="mousedown"&&A&&E(T.element)}function i(T,w){var A;let E=(A=T.quirks)==null?void 0:A.isCKEditorFrame;w.type==="click"&&E&&document.body.focus()}function n(T){let w=[];for(;T!=null&&T.parentNode;)w.push(T),T=T.parentNode;return w}function o(T){let w={status:"done",result:T,success:!0,...b.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(w)}function a(T){T||="",e({status:"failed",result:T,success:!1})}function c(T){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),T.dispatchEvent(w)}function l(T){let w={},E=T.getBoundingClientRect(),A=E.left+E.width/2,_=E.top+E.height/2,S=f("mousemove",w,A,_,0);T.dispatchEvent(S)}function d(T,w){function E(S,C,D){return D>S&&D<C}let A=T.pointerPosition||{},_=w.getBoundingClientRect(),B=A.originX&&E(_.left,_.left+_.width,A.originX)?A.originX:_.left+_.width/2,V=A.originY&&E(_.top,_.top+_.height,A.originY)?A.originY:_.top+_.height/2;return{x:B,y:V}}function m(T,w,E){return{screenX:0,screenY:0,clientX:w,clientY:E,ctrlKey:Boolean(T.ctrl),altKey:Boolean(T.alt),shiftKey:Boolean(T.shift),metaKey:Boolean(T.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(T,w,E,A){if(!window.PointerEvent)return;let _=m(w,E,A);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(T,_)}function f(T,w,E,A,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(T,!0,!0,document.defaultView,1,0,0,E,A,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),_,document.body?document.body.parentNode:document.documentElement),B}function h(T,w){let E=["pointerup","pointerdown","pointermove"],A=w.modifiers||{},_=d(T,w.element),B=w.button||0,V=T.event;return E.includes(V)?u(V,A,_.x,_.y):f(V,A,_.x,_.y,B)}function g(){var w;let T=document.activeElement;for(;(w=T.shadowRoot)!=null&&w.activeElement;)T=T.shadowRoot.activeElement;return T}function y(T){T.events.map(w=>{try{return h(w,T)}catch{return}}).filter(Boolean).forEach(w=>{T.element.dispatchEvent(w),r(T,w),i(T,w)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let b={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!b.element){a("element not found");return}c(b.element),l(b.element);try{y(b);let T=g(),w=b.quirks,E=w==null?void 0:w.isReactSelect,A=w==null?void 0:w.isCKEditorFrame;!E&&!A&&dispatchFocus(s.elementToFocusLocatedElement,T),o()}catch(T){a(T.toString())}}});var cy={};z(cy,{doDragPath:()=>PE});var PE,ly=I(()=>{"use strict";PE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",i=40;window.__unloadNavigator=n,window.addEventListener("unload",window.__unloadNavigator);function n(T){e({status:"done",result:T,success:!0})}function o(T){T||="",e({status:"failed",result:T,success:!1})}function a(T){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),T.dispatchEvent(w)}function c(T){let w={},E=T.getBoundingClientRect(),A=E.left+E.width/2,_=E.top+E.height/2,S=u("mousemove",w,A,_,0);T.dispatchEvent(S)}function l(T,w){function E(S,C,D){return D>S&&D<C}let A=T.pointerPosition||{};if(b.isDrag)return{x:A.originX||0,y:A.originY||0};let _=w.getBoundingClientRect(),B=A.originX&&E(_.left,_.left+_.width,A.originX)?A.originX:_.left+_.width/2,V=A.originY&&E(_.top,_.top+_.height,A.originY)?A.originY:_.top+_.height/2;return{x:B,y:V}}function d(T,w,E){return{screenX:0,screenY:0,clientX:w,clientY:E,ctrlKey:Boolean(T.ctrl),altKey:Boolean(T.alt),shiftKey:Boolean(T.shift),metaKey:Boolean(T.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(T,w,E,A,_){if(r){let V=d(w,E,A);return V.pointerType="mouse",V.isPrimary=!0,new window.PointerEvent(T,V)}let B=document.createEvent("PointerEvent");return B.initPointerEvent(T,!0,!0,document.defaultView,1,0,0,E,A,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),B}function u(T,w,E,A,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(T,!0,!0,document.defaultView,1,0,0,E,A,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),_,document.body?document.body.parentNode:document.documentElement),B}function f(T,w){let E=["pointerup","pointerdown","pointermove"],A=w.modifiers||{},_=l(T,w.element),B=w.button||0,V=T.event;return E.includes(V)?m(V,A,_.x,_.y,B):u(V,A,_.x,_.y,B)}function h(T,w){function E(){return T.event==="click"&&w.isDrag&&!w.allEventsOnSameElement}return E()}function g(T,w,E){try{let A=f(w.events[T],w);h(A,w)||w.element.dispatchEvent(A)}catch{}if(T+1===w.events.length)E();else{let A=Math.min(w.events[T+1].timeStamp-w.events[T].timeStamp,i);setTimeout(()=>{g(T+1,w,E)},A)}}function y(T,w){g(0,T,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w()})}let b={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(!b.element){o("element not found");return}a(b.element),c(b.element),y(b,()=>{n()})}});var Qi,pa,uy=I(()=>{"use strict";Qi=R(require("lodash"));me();sy();de();ny();pa=class extends q{getDnDRectsAndOffsets(e,t,r,i){let n=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(i,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:n.x,fromY:n.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),i=t.data.timeToPlayStep+3e3,n=e.events;if(!(n!=null&&n.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:n,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(ay(),oy)),Promise.resolve().then(()=>(ji(),Bi))]),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,i,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,i=this.isWithinBounds(r.left,r.left+r.width,e.originX),n=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=i?0:r.left+r.width/2-e.originX,a=n?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=Zi.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:i}=this.step,n=e.find(l=>["mousedown","pointerdown"].includes(l.event));if(n){let l=e.indexOf(n);e.splice(l,0,this.generateEventOfType(n,"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(Zi.findLastIndex(e,l=>l.event==="mousemove")||o&&Zi.findLastIndex(e,l=>l.event==="pointermove"));a&&c>0&&!t&&e.splice(c+1,0,this.generateEventOfType(a,"mouseover")),r&&!i&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var d,m;let{step:e,context:t}=this,r=this.getTarget(),i=t.data.timeToPlayStep+3e3;if(!((d=e.events)!=null&&d.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let n=e.events,o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:n,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(),py)),Promise.resolve().then(()=>($i(),ji))]),l=`
229
+ `;try{return(d=(await this.driver.executeCodeAsync(l,i,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,i=this.isWithinBounds(r.left,r.left+r.width,e.originX),n=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=i?0:r.left+r.width/2-e.originX,a=n?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=Qi.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:i}=this.step,n=e.find(l=>["mousedown","pointerdown"].includes(l.event));if(n){let l=e.indexOf(n);e.splice(l,0,this.generateEventOfType(n,"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(Qi.findLastIndex(e,l=>l.event==="mousemove")||o&&Qi.findLastIndex(e,l=>l.event==="pointermove"));a&&c>0&&!t&&e.splice(c+1,0,this.generateEventOfType(a,"mouseover")),r&&!i&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var d,m;let{step:e,context:t}=this,r=this.getTarget(),i=t.data.timeToPlayStep+3e3;if(!((d=e.events)!=null&&d.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let n=e.events,o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:n,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(ly(),cy)),Promise.resolve().then(()=>(ji(),Bi))]),l=`
230
230
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
231
231
  var dispatchFocus = ${c.toString()};
232
232
  var doDragPath = ${a.toString()};
233
233
  return doDragPath.apply(null, arguments);
234
234
  `;try{return(m=(await this.driver.executeCodeAsync(l,i,o)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset:i,rect:n}=e,o={frameOffset:{x:n.left-i.left,y:n.top-i.top},rect:i,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,i)};if(O.flags.skipFileInputClicks.isEnabled()&&e.tagName==="INPUT"&&(e.elementSymbol.includes('type="file"')||e.elementSymbol.includes("type='file'")||e.elementSymbol.includes("type=file")))return{keep:!0,success:"skipped",reason:"Clicking on input type=file is disabled"};if(this.step.isDoubleClick){let d={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,d,o)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(O.flags.usePortedHtml5DragDrop.isEnabled()){let h=this.generateHTML5DragEventSequence(),g=this.context.data.timeToPlayStep+3e3,y=this.getTarget(),v={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:h,eventData:{modifiers:this.step.modifiers,button:this.step.button},quirks:this.step.quirks,isDrag:this.step.isDrag,useRecordedMousedown:this.step.useRecordedMousedown,allEventsOnSameElement:this.step.allEventsOnSameElement,elementToFocusLocatedElement:y.elementToFocusLocatedElement,trackActiveElement:this.step.trackActiveElement,locatedElement:y.locatedElement,isRoot:y.isRoot},b=`
235
235
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
236
- var dnd = ${ay.toString()};
236
+ var dnd = ${iy.toString()};
237
237
  var eventData = arguments[0];
238
238
  var done = arguments[1];
239
239
  return dnd.call(null, eventData, done);
240
240
  `;return this.driver.executeCodeAsync(b,g,v)}let u=`
241
241
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
242
- var dnd = ${ny.toString()};
242
+ var dnd = ${ry.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(i=>["dragend","drop"].includes(i.event)),r=e[t-1];if(!r||r.event!=="dragover"){let i={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,i)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let i=n=>n.fireOnTarget||["drop","dragenter"].includes(n.event);return e.forEach(n=>Object.assign(n,{locatedElement:i(n)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(i=>i.event!=="mousemove"&&i.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(i=>Object.assign(i,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var en,fy=I(()=>{"use strict";me();en=class extends q{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:i,commonConstants:n}}=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 i.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:n.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:n.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var gy,_E,ma,hy=I(()=>{"use strict";gy=R(require("lodash"));me();W();_E=P("evaluate-expression-step-action"),ma=class extends q{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:i}=this;try{_E.info("runner running incoming params evaluation");let n=t.incomingParams||{};gy.isEmpty(n)&&(n=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,i));let o=["context",...n.as.functionParameters],a=[t,...n.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(n){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:n.toString()},success:!1}}}}});var yy={};z(yy,{setText:()=>DE});var DE,by=I(()=>{"use strict";DE=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),i={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){xe()},window.addEventListener("unload",window.__unloadNavigator);let n=new Set(["keydown","keyup","keypress"]),o=15;function a(k){try{if(!t)return;let L=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return k.eventData&&(L.data=k.eventData.data),L}catch{}}function c(k){try{let L=document.createEvent("TextEvent");L.data=k.eventData.data;let $=1,Y=k.eventData.locale||"en-US";return L.initTextEvent("textInput",!0,!0,window,k.eventData.data,$,Y),L}catch{}}function l(k){return a(k)||c(k)}function d(k,L,$){try{return new KeyboardEvent(k,{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(k,L,$){try{let Y=document.createEvent("KeyboardEvent");return Y.initKeyEvent(k,!0,!0,null,Boolean($.ctrl),Boolean($.alt),Boolean($.shift),Boolean($.meta),L.key||"",0),Y}catch{}}function u(k,L,$){try{let Y=document.createEvent("Events");return Y.initEvent(k,!0,!0),Object.assign(Y,{altKey:Boolean($.alt),ctrlKey:Boolean($.ctrl),metaKey:Boolean($.meta),shiftKey:Boolean($.shift),keyCode:L.key||""}),Y}catch{}}function f(k,L,$){return d(k,L,$)||m(k,L,$)||u(k,L,$)}function h(k){if(!n.has(k.event))return null;let L=k.eventData,$=L.modifiers||{},Y=f(k.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(k){return k.event==="textInput"?l(k):h(k)}function y(k,L){return(()=>{var Y;return k.event==="textInput"&&!((Y=L.quirks)!=null&&Y.isAuth0Form)})()}function v(k,L){return k.event==="keyup"&&L.event==="keydown"?o:0}function b(k,L){let $=v(k,L);return Math.min(L.timeStamp-k.timeStamp,$)}function T(k){let L=Object.getOwnPropertyDescriptor(k,"value");if(!L)return;let $=k.value;k.value=`${$}#`,L.configurable&&delete k.value,k.value=$;let Y=document.createEvent("HTMLEvents");Y.initEvent("input",!0,!1),k.dispatchEvent(Y),Object.defineProperty(k,"value",L)}function w(k){if(j(k.element))try{if(T(k.element),t)k.element.dispatchEvent(new Event("change"));else{let L=document.createEvent("HTMLEvents");L.initEvent("change",!1,!0),k.element.dispatchEvent(L)}}catch{}}function E(k,L,$){$?setTimeout(()=>{N(k)},b(L,$)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w(k),xe())}function C(k,L){return(k==="change"||k==="blur")&&L.element.tagName==="OPTION"}function _(k,L,$){return C(k.type,L)?L.element.parentElement:$.locatedElement?getLocatedElement($.locatedElement):L.element}function B(k,L){let $=k.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 V(k,L){if(!(!k||!L)){if(!isNaN(L.start))Object.assign(k,{selectionStart:L.start,selectionEnd:L.end});else if(!isNaN(L.nodeOffset)){let $;if(k.firstChild?$=B(k,{offset:L.nodeOffset}):$=k,$){let Y=window.getSelection(),Le=document.createRange();try{Y.removeAllRanges(),Le.setStart($,L.textOffset),Le.setEnd($,L.textOffset),Y.addRange(Le)}catch{}}}}}function S(k,L){return k==="submit"&&Boolean(L.action)}function A(k,L,$){if(L.isFocusable&&L.isSelectable(k)&&k.type!=="submit")try{V(L.element,$.eventData.selection)}catch{}let Y=_(k,L,$);if(!Y)throw new Error("could not find element");S(k.type,Y)?Y.submit():Y.dispatchEvent(k)}function N(k){let L,$=k.events[k.eventIndex],Y=k.events[++k.eventIndex];try{L=g($)}catch(Le){return Te(`exception in get event in text step:${Le.message}`)}if(y($,k))return E(k,$,Y);if(L)try{A(L,k,$)}catch(Le){return Te(`exception in executeEvent in text step:${Le.message}`)}else if(k.noEventExecuter)k.noEventExecuter(k,$);else return Te(`cannot execute event ${$.event}`);E(k,$,Y)}function j(k){let L=k.tagName;return L==="INPUT"||L==="TEXTAREA"}function H(k){return k.getAttribute?Boolean(k.getAttribute("contenteditable")==="true"):!1}function G(k,L){if(j(k.element)){k.element.value=L.eventData.text;let $=document.createEvent("Event");$.initEvent("input",!0,!1),k.element.dispatchEvent($)}else k.isContentEditable&&(k.element.innerHTML=L.eventData.text)}function J(){var L;let k=document.activeElement;for(;(L=k.shadowRoot)!=null&&L.activeElement;)k=k.shadowRoot.activeElement;return k}function xe(k){let L={status:"done",result:k,success:!0,...i.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(L)}function Te(k){k||="";let L={status:"failed",result:k,success:!1,...i.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(L)}try{let k=j(i.element);i.isContentEditable=H(i.element),!k&&!i.isContentEditable&&(i.isNonTextableElemnet=!0),i.isFocusable=k||i.isContentEditable,i.isSelectable=L=>L.type!=="keyup",i.noEventExecuter=G}catch(k){Te(`exception in set text step:${k.message}`);return}let gr=J();dispatchFocus(s.elementToFocusLocatedElement,gr),N(i)}});var fa,Ty=I(()=>{"use strict";me();F();fa=class extends q{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:i,sessionPlayerInit:n}=this,o=this.getTarget(),a=i.data.timeToPlayStep+3e3,{setTextDraftJs:c}=n.codeSnippets;if(o.isDraftEditor&&c)return this.driver.executeJS(c(o.locatedElement,i.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(()=>(by(),yy)),Promise.resolve().then(()=>($i(),ji))]),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(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(i=>["dragend","drop"].includes(i.event)),r=e[t-1];if(!r||r.event!=="dragover"){let i={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,i)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let i=n=>n.fireOnTarget||["drop","dragenter"].includes(n.event);return e.forEach(n=>Object.assign(n,{locatedElement:i(n)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(i=>i.event!=="mousemove"&&i.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(i=>Object.assign(i,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var Zi,py=I(()=>{"use strict";me();Zi=class extends q{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:i,commonConstants:n}}=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 i.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:n.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:n.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var dy,kE,da,my=I(()=>{"use strict";dy=R(require("lodash"));me();W();kE=P("evaluate-expression-step-action"),da=class extends q{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:i}=this;try{kE.info("runner running incoming params evaluation");let n=t.incomingParams||{};dy.isEmpty(n)&&(n=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,i));let o=["context",...n.as.functionParameters],a=[t,...n.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(n){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:n.toString()},success:!1}}}}});var fy={};z(fy,{setText:()=>OE});var OE,gy=I(()=>{"use strict";OE=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),i={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){xe()},window.addEventListener("unload",window.__unloadNavigator);let n=new Set(["keydown","keyup","keypress"]),o=15;function a(k){try{if(!t)return;let L=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return k.eventData&&(L.data=k.eventData.data),L}catch{}}function c(k){try{let L=document.createEvent("TextEvent");L.data=k.eventData.data;let $=1,X=k.eventData.locale||"en-US";return L.initTextEvent("textInput",!0,!0,window,k.eventData.data,$,X),L}catch{}}function l(k){return a(k)||c(k)}function d(k,L,$){try{return new KeyboardEvent(k,{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(k,L,$){try{let X=document.createEvent("KeyboardEvent");return X.initKeyEvent(k,!0,!0,null,Boolean($.ctrl),Boolean($.alt),Boolean($.shift),Boolean($.meta),L.key||"",0),X}catch{}}function u(k,L,$){try{let X=document.createEvent("Events");return X.initEvent(k,!0,!0),Object.assign(X,{altKey:Boolean($.alt),ctrlKey:Boolean($.ctrl),metaKey:Boolean($.meta),shiftKey:Boolean($.shift),keyCode:L.key||""}),X}catch{}}function f(k,L,$){return d(k,L,$)||m(k,L,$)||u(k,L,$)}function h(k){if(!n.has(k.event))return null;let L=k.eventData,$=L.modifiers||{},X=f(k.event,L,$);return Object.defineProperties(X,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(X,{_keyCode_:L.keyCode,_charCode_:L.charCode||0}),X}function g(k){return k.event==="textInput"?l(k):h(k)}function y(k,L){return(()=>{var X;return k.event==="textInput"&&!((X=L.quirks)!=null&&X.isAuth0Form)})()}function v(k,L){return k.event==="keyup"&&L.event==="keydown"?o:0}function b(k,L){let $=v(k,L);return Math.min(L.timeStamp-k.timeStamp,$)}function T(k){let L=Object.getOwnPropertyDescriptor(k,"value");if(!L)return;let $=k.value;k.value=`${$}#`,L.configurable&&delete k.value,k.value=$;let X=document.createEvent("HTMLEvents");X.initEvent("input",!0,!1),k.dispatchEvent(X),Object.defineProperty(k,"value",L)}function w(k){if(j(k.element))try{if(T(k.element),t)k.element.dispatchEvent(new Event("change"));else{let L=document.createEvent("HTMLEvents");L.initEvent("change",!1,!0),k.element.dispatchEvent(L)}}catch{}}function E(k,L,$){$?setTimeout(()=>{D(k)},b(L,$)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w(k),xe())}function A(k,L){return(k==="change"||k==="blur")&&L.element.tagName==="OPTION"}function _(k,L,$){return A(k.type,L)?L.element.parentElement:$.locatedElement?getLocatedElement($.locatedElement):L.element}function B(k,L){let $=k.firstChild,X;for(;$;){if($.nodeType===3){if(L.offset--<=0)return $}else if($.nodeType===1&&(X=B($,L),X))return X;$=$.nextSibling}return null}function V(k,L){if(!(!k||!L)){if(!isNaN(L.start))Object.assign(k,{selectionStart:L.start,selectionEnd:L.end});else if(!isNaN(L.nodeOffset)){let $;if(k.firstChild?$=B(k,{offset:L.nodeOffset}):$=k,$){let X=window.getSelection(),De=document.createRange();try{X.removeAllRanges(),De.setStart($,L.textOffset),De.setEnd($,L.textOffset),X.addRange(De)}catch{}}}}}function S(k,L){return k==="submit"&&Boolean(L.action)}function C(k,L,$){if(L.isFocusable&&L.isSelectable(k)&&k.type!=="submit")try{V(L.element,$.eventData.selection)}catch{}let X=_(k,L,$);if(!X)throw new Error("could not find element");S(k.type,X)?X.submit():X.dispatchEvent(k)}function D(k){let L,$=k.events[k.eventIndex],X=k.events[++k.eventIndex];try{L=g($)}catch(De){return Te(`exception in get event in text step:${De.message}`)}if(y($,k))return E(k,$,X);if(L)try{C(L,k,$)}catch(De){return Te(`exception in executeEvent in text step:${De.message}`)}else if(k.noEventExecuter)k.noEventExecuter(k,$);else return Te(`cannot execute event ${$.event}`);E(k,$,X)}function j(k){let L=k.tagName;return L==="INPUT"||L==="TEXTAREA"}function H(k){return k.getAttribute?Boolean(k.getAttribute("contenteditable")==="true"):!1}function G(k,L){if(j(k.element)){k.element.value=L.eventData.text;let $=document.createEvent("Event");$.initEvent("input",!0,!1),k.element.dispatchEvent($)}else k.isContentEditable&&(k.element.innerHTML=L.eventData.text)}function J(){var L;let k=document.activeElement;for(;(L=k.shadowRoot)!=null&&L.activeElement;)k=k.shadowRoot.activeElement;return k}function xe(k){let L={status:"done",result:k,success:!0,...i.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(L)}function Te(k){k||="";let L={status:"failed",result:k,success:!1,...i.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(L)}try{let k=j(i.element);i.isContentEditable=H(i.element),!k&&!i.isContentEditable&&(i.isNonTextableElemnet=!0),i.isFocusable=k||i.isContentEditable,i.isSelectable=L=>L.type!=="keyup",i.noEventExecuter=G}catch(k){Te(`exception in set text step:${k.message}`);return}let fr=J();dispatchFocus(s.elementToFocusLocatedElement,fr),D(i)}});var ma,hy=I(()=>{"use strict";me();F();ma=class extends q{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:i,sessionPlayerInit:n}=this,o=this.getTarget(),a=i.data.timeToPlayStep+3e3,{setTextDraftJs:c}=n.codeSnippets;if(o.isDraftEditor&&c)return this.driver.executeJS(c(o.locatedElement,i.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(()=>(gy(),fy)),Promise.resolve().then(()=>(ji(),Bi))]),u=`
246
246
  var getLocatedElement = ${n.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 pe(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:()=>LE});var LE,vy=I(()=>{"use strict";LE=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 v={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(v))}catch(y){let v=y.message.toLowerCase().includes("quota"),b=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||v||b){let T=document.head.querySelector("#testim-storage-backup");T||(T=document.createElement("meta"),T.id="testim-storage-backup",document.head.append(T));let E={...JSON.parse(T.getAttribute(f)||"{}"),...u};if(T.setAttribute(f,JSON.stringify(E)),v||b)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 i(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let n={},o={},a={},c=s.functionParams,l=s.transactionId;try{let m=r(s);m.push(n,o,a);let u=((d=s.function)==null?void 0:d.params)||c,h=(e||i(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:n,exportsTest:o,exportsGlobal:a}})},g=>{t(l,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:n,exportsTest:o,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:h,exports:n,exportsTest:o,exportsGlobal:a}})}catch(m){t(l,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:n,exportsTest:o,exportsGlobal:a}})}}});var ga,tn,lr,ha=I(()=>{"use strict";ga=R(require("lodash"));F();me();W();de();tn=P("base-js-step-action"),lr=class extends q{isExceedingMaxResultSize(t,r){var i;try{let n=(i=r.project.defaults)==null?void 0:i.enforceMaximumJsResultSize,o=O.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>o;return n?a:(a&&tn.warn(`js result size exceeded ${o}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let i=`data-testim-${r}`;try{return window.sessionStorage.getItem(i)}catch(n){if(n.message.includes("sessionStorage")||n.message.includes("The operation is insecure")){let o=document.head.querySelector("#testim-storage-backup");return o?o.getAttribute(i):"{}"}throw n}},t)}constructJSFunParams(t){let r=t.incomingParams,i=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],n=[t.context,...r.as.functionArguments];return i.push(t.code),n.forEach(o=>{ga.isObject(o)&&jn(o,"seleniumElement",ga.isEqual)}),{function:{params:i,args:n},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:i,step:{id:n=""}}=this,o=r.config.retryTimeout,a=r.data.timeToPlayStep-o,c=async()=>{let l;try{l=await this.executeGetStatus(t)}catch(u){tn.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{tn.warn("non object value",{selRes:l}),d={status:"exception"}}let m=i.abortedSteps.find(u=>u.id===n);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 pe(o),c()):{success:!0})};return c()}async executeInAut(t){let r=O.flags.experimentalPreCodeCompilation.isEnabled(),i=O.flags.experimentalAsyncCustomCode.isEnabled(),n=this.constructJSFunParams(t),o=n.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=n.function.params.slice(0,-1);a=i?`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(Fe(t.seleniumElement),e[r]),r<e.length-1&&await pe(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 yy={};z(yy,{runCode:()=>_E});var _E,by=I(()=>{"use strict";_E=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 v={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(v))}catch(y){let v=y.message.toLowerCase().includes("quota"),b=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||v||b){let T=document.head.querySelector("#testim-storage-backup");T||(T=document.createElement("meta"),T.id="testim-storage-backup",document.head.append(T));let E={...JSON.parse(T.getAttribute(f)||"{}"),...u};if(T.setAttribute(f,JSON.stringify(E)),v||b)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 i(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let n={},o={},a={},c=s.functionParams,l=s.transactionId;try{let m=r(s);m.push(n,o,a);let u=((d=s.function)==null?void 0:d.params)||c,h=(e||i(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:n,exportsTest:o,exportsGlobal:a}})},g=>{t(l,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:n,exportsTest:o,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:h,exports:n,exportsTest:o,exportsGlobal:a}})}catch(m){t(l,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:n,exportsTest:o,exportsGlobal:a}})}}});var fa,en,lr,ga=I(()=>{"use strict";fa=R(require("lodash"));F();me();W();de();en=P("base-js-step-action"),lr=class extends q{isExceedingMaxResultSize(t,r){var i;try{let n=(i=r.project.defaults)==null?void 0:i.enforceMaximumJsResultSize,o=O.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>o;return n?a:(a&&en.warn(`js result size exceeded ${o}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let i=`data-testim-${r}`;try{return window.sessionStorage.getItem(i)}catch(n){if(n.message.includes("sessionStorage")||n.message.includes("The operation is insecure")){let o=document.head.querySelector("#testim-storage-backup");return o?o.getAttribute(i):"{}"}throw n}},t)}constructJSFunParams(t){let r=t.incomingParams,i=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],n=[t.context,...r.as.functionArguments];return i.push(t.code),n.forEach(o=>{fa.isObject(o)&&Bn(o,"seleniumElement",fa.isEqual)}),{function:{params:i,args:n},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:i,step:{id:n=""}}=this,o=r.config.retryTimeout,a=r.data.timeToPlayStep-o,c=async()=>{let l;try{l=await this.executeGetStatus(t)}catch(u){en.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{en.warn("non object value",{selRes:l}),d={status:"exception"}}let m=i.abortedSteps.find(u=>u.id===n);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 pe(o),c()):{success:!0})};return c()}async executeInAut(t){let r=O.flags.experimentalPreCodeCompilation.isEnabled(),i=O.flags.experimentalAsyncCustomCode.isEnabled(),n=this.constructJSFunParams(t),o=n.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=n.function.params.slice(0,-1);a=i?`async function(${m.join(",")}) {
253
253
  ${t.code}
254
254
  };`:`function(${m.join(",")}) {
255
255
  ${t.code}
256
- };`,n.function.params.pop()}let{codeSnippets:c}=this.sessionPlayerInit,{runCode:l}=await Promise.resolve().then(()=>(vy(),wy)),d=`
256
+ };`,n.function.params.pop()}let{codeSnippets:c}=this.sessionPlayerInit,{runCode:l}=await Promise.resolve().then(()=>(by(),yy)),d=`
257
257
  ${o?`var getLocatedElement = ${c.getLocatedElementCode};`:";"}
258
258
  var runCode = ${l.toString()};
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,n);try{return await this.driver.executeJS(d,n)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:i}=this,{result:n={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:c}=t;n.exports&&(i.data.exports=n.exports);let l={nodeVersion:a,tstConsoleLogs:o,data:i.data};return this.isFailedResult(n.resultValue)?{...l,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:n,tstConsoleLogs:o},i)?{...l,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...l,success:!0,exportsTest:n.exportsTest,exportsGlobal:n.exportsGlobal,...c&&{navigateToDifferentDomain:c}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:i}=this;if(t.type==="promise")return{data:i.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:n={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:i.data,exportsGlobal:n.exportsGlobal,exportsTest:n.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:n.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var n;let i=t.id;return t.id||(tn.warn("step.id doesn't exist on step",{step:t,context:r}),i=r.stepResultId),"stepResultId"in r&&((n=r.stepResultId)!=null&&n.length)?i=r.stepResultId:tn.warn("stepResultId is not present in context",{step:t,context:r}),`${r.testResultId}:${i}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let i=await this.driver.getBrowserAndOS(),n={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:i.browser,browserMajor:i.browserMajor};r.isPendingPromise||await this.executeInAut(n);let o=await this.checkStatus(n.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var zt,Sy=I(()=>{"use strict";ha();zt=class extends lr{isFailedResult(e){return e===!1}}});var Os,Ey=I(()=>{"use strict";ha();Os=class extends lr{isFailedResult(e){return!e}}});var ya,Iy=I(()=>{"use strict";me();F();la();ya=class extends q{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(Xi[t]),this.setWithValueApi(e)}}});var ba,Ry=I(()=>{"use strict";me();la();ba=class extends q{async performAction(){var n,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((n=this.step.keys)!=null&&n.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 i=r.keyCode;if(i>=32&&i<=127)t.push(r.key);else if(Xi[i])t.push(Xi[i]);else throw new Error(`Invalid key with keyCode ${i}.`);return await this.driver.sendKeyboardShortcut(t)}}});var xy={};z(xy,{selectOption:()=>NE});function NE(s,e){function t(r,i){let n=Element.prototype.matches,o=n&&isNativeFunction(n)?n:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,i))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 i=t(r,"select");return i?(i.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){i.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 Cy=I(()=>{"use strict"});var Ta,Ay=I(()=>{"use strict";me();F();de();Ta=class extends q{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,n=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&n>=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(()=>(Cy(),xy)),l=O.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
262
+ `;if(!r)return this.driver.executeJS(d,n);try{return await this.driver.executeJS(d,n)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:i}=this,{result:n={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:c}=t;n.exports&&(i.data.exports=n.exports);let l={nodeVersion:a,tstConsoleLogs:o,data:i.data};return this.isFailedResult(n.resultValue)?{...l,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:n,tstConsoleLogs:o},i)?{...l,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...l,success:!0,exportsTest:n.exportsTest,exportsGlobal:n.exportsGlobal,...c&&{navigateToDifferentDomain:c}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:i}=this;if(t.type==="promise")return{data:i.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:n={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:i.data,exportsGlobal:n.exportsGlobal,exportsTest:n.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:n.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var n;let i=t.id;return t.id||(en.warn("step.id doesn't exist on step",{step:t,context:r}),i=r.stepResultId),"stepResultId"in r&&((n=r.stepResultId)!=null&&n.length)?i=r.stepResultId:en.warn("stepResultId is not present in context",{step:t,context:r}),`${r.testResultId}:${i}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let i=await this.driver.getBrowserAndOS(),n={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:i.browser,browserMajor:i.browserMajor};r.isPendingPromise||await this.executeInAut(n);let o=await this.checkStatus(n.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var zt,Ty=I(()=>{"use strict";ga();zt=class extends lr{isFailedResult(e){return e===!1}}});var Cs,wy=I(()=>{"use strict";ga();Cs=class extends lr{isFailedResult(e){return!e}}});var ha,vy=I(()=>{"use strict";me();F();ca();ha=class extends q{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(Xi[t]),this.setWithValueApi(e)}}});var ya,Sy=I(()=>{"use strict";me();ca();ya=class extends q{async performAction(){var n,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((n=this.step.keys)!=null&&n.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 i=r.keyCode;if(i>=32&&i<=127)t.push(r.key);else if(Xi[i])t.push(Xi[i]);else throw new Error(`Invalid key with keyCode ${i}.`);return await this.driver.sendKeyboardShortcut(t)}}});var Ey={};z(Ey,{selectOption:()=>LE});function LE(s,e){function t(r,i){let n=Element.prototype.matches,o=n&&isNativeFunction(n)?n:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,i))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 i=t(r,"select");return i?(i.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){i.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 Iy=I(()=>{"use strict"});var ba,Ry=I(()=>{"use strict";me();F();de();ba=class extends q{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,n=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&n>=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(()=>(Iy(),Ey)),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()};
266
266
  return selectOption.apply(null, arguments);
267
- `;return(f=(await this.driver.executeJS(d,r,l)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var wa,Py=I(()=>{"use strict";me();wa=class extends q{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var ME,va,ky=I(()=>{"use strict";me();ME=(s,e,t,r)=>({x:t,y:r,width:e,height:s,get top(){return this.y},get left(){return this.x},get right(){return this.x+this.width},get bottom(){return this.y+this.height},toJSON(){}}),va=class extends q{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:i}=e,{width:n,height:o}=i,a=n/2,c=o/2,l=this.step.element.clickOffset;if(l&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:u}=l;this.sessionPlayerInit.utils.isWithinTargetRect(ME(o,n,0,0),m,u)&&(a=m,c=u)}let d={frameOffset:{x:i.left-r.left,y:i.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(c)}};return await this.driver.hover(t,d),{success:!0}}}});var Oy={};z(Oy,{wheel:()=>FE});var FE,_y=I(()=>{"use strict";FE=function(s,e){function r(a,c){function l(h,g,y){return y>h&&y<g}let d=a.pointerPosition||{},m=c.getBoundingClientRect(),u=d.originX&&l(m.left,m.left+m.width,d.originX)?d.originX:m.left+m.width/2,f=d.originY&&l(m.top,m.top+m.height,d.originY)?d.originY:m.top+m.height/2;return{x:u,y:f}}function i(a,c,l){let d=r(a,l),m=(c==null?void 0:c.modifiers)||{},u={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:d.x,clientY:d.y,bubbles:!0,cancelable:!0,ctrl:Boolean(m.ctrl),alt:Boolean(m.alt),shift:Boolean(m.shift),meta:Boolean(m.meta)};return new WheelEvent("wheel",u)}function n(a,c){if(a.length===0){e({state:"success"});return}if(!c)throw new Error("element not found");let l=a.shift(),d=i(l,s.eventData,c),m=a[0]?Math.min(a[0].timeStamp-l.timeStamp,200):200;c.dispatchEvent(d),setTimeout(()=>{n(a,c)},m)}let o=getLocatedElement(s.locatedElement);n(s.events,o)}});var Sa,Dy=I(()=>{"use strict";me();Sa=class extends q{async performAction(){var m;let{step:e,context:t}=this,{events:r,modifiers:i,button:n}=e;if(!(r!=null&&r.length))return;let o={events:r,eventData:{modifiers:i,button:n},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:c}=await Promise.resolve().then(()=>(_y(),Oy)),l=`
267
+ `;return(f=(await this.driver.executeJS(d,r,l)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var Ta,xy=I(()=>{"use strict";me();Ta=class extends q{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var DE,wa,Ay=I(()=>{"use strict";me();DE=(s,e,t,r)=>({x:t,y:r,width:e,height:s,get top(){return this.y},get left(){return this.x},get right(){return this.x+this.width},get bottom(){return this.y+this.height},toJSON(){}}),wa=class extends q{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:i}=e,{width:n,height:o}=i,a=n/2,c=o/2,l=this.step.element.clickOffset;if(l&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:u}=l;this.sessionPlayerInit.utils.isWithinTargetRect(DE(o,n,0,0),m,u)&&(a=m,c=u)}let d={frameOffset:{x:i.left-r.left,y:i.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(c)}};return await this.driver.hover(t,d),{success:!0}}}});var Cy={};z(Cy,{wheel:()=>NE});var NE,Py=I(()=>{"use strict";NE=function(s,e){function r(a,c){function l(h,g,y){return y>h&&y<g}let d=a.pointerPosition||{},m=c.getBoundingClientRect(),u=d.originX&&l(m.left,m.left+m.width,d.originX)?d.originX:m.left+m.width/2,f=d.originY&&l(m.top,m.top+m.height,d.originY)?d.originY:m.top+m.height/2;return{x:u,y:f}}function i(a,c,l){let d=r(a,l),m=(c==null?void 0:c.modifiers)||{},u={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:d.x,clientY:d.y,bubbles:!0,cancelable:!0,ctrl:Boolean(m.ctrl),alt:Boolean(m.alt),shift:Boolean(m.shift),meta:Boolean(m.meta)};return new WheelEvent("wheel",u)}function n(a,c){if(a.length===0){e({state:"success"});return}if(!c)throw new Error("element not found");let l=a.shift(),d=i(l,s.eventData,c),m=a[0]?Math.min(a[0].timeStamp-l.timeStamp,200):200;c.dispatchEvent(d),setTimeout(()=>{n(a,c)},m)}let o=getLocatedElement(s.locatedElement);n(s.events,o)}});var va,ky=I(()=>{"use strict";me();va=class extends q{async performAction(){var m;let{step:e,context:t}=this,{events:r,modifiers:i,button:n}=e;if(!(r!=null&&r.length))return;let o={events:r,eventData:{modifiers:i,button:n},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:c}=await Promise.resolve().then(()=>(Py(),Cy)),l=`
268
268
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
269
269
  var wheel = ${c.toString()};
270
270
  var eventData = arguments[0];
271
271
  var done = arguments[1];
272
272
  return wheel.call(null, eventData, done);
273
- `;return{success:((m=(await this.driver.executeCodeAsync(l,a,o)).value)==null?void 0:m.state)==="success"}}}});var Ly={};z(Ly,{downloadFileAndFireDropEvent:()=>UE});var UE,Ny=I(()=>{"use strict";UE=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let o=-1,a=0,c=[],l={endWithCallback:void 0,waitOn(){let d=++o;return function(m){d in c||(c[d]=m,a++,e.length===a&&l.endWithCallback(c))}},endWith(d){l.endWithCallback=d}};return l}function i(o,a,c){let l=new XMLHttpRequest;l.open("GET",o),l.responseType="blob",l.onload=function(){if(this.status>=200&&this.status<300)c({blob:l.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},l.onerror=function(){throw new Error("Failed to load blob")},l.send()}let n=r();e.forEach(o=>{i(o.url,o.name,n.waitOn())}),n.endWith(o=>{let a=createDropEvent(o);t.dispatchEvent(a)})}});var BE,Ea,My=I(()=>{"use strict";me();W();de();BE=P("drop-file-step-action"),Ea=class extends q{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:i}=this,n=this.getTarget(),o=O.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,i.fileUrls,this.stepActionUtils.testimServicesApi,o,BE),{downloadFileAndFireDropEvent:c}=await Promise.resolve().then(()=>(Ny(),Ly)),l=`
273
+ `;return{success:((m=(await this.driver.executeCodeAsync(l,a,o)).value)==null?void 0:m.state)==="success"}}}});var Oy={};z(Oy,{downloadFileAndFireDropEvent:()=>ME});var ME,_y=I(()=>{"use strict";ME=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let o=-1,a=0,c=[],l={endWithCallback:void 0,waitOn(){let d=++o;return function(m){d in c||(c[d]=m,a++,e.length===a&&l.endWithCallback(c))}},endWith(d){l.endWithCallback=d}};return l}function i(o,a,c){let l=new XMLHttpRequest;l.open("GET",o),l.responseType="blob",l.onload=function(){if(this.status>=200&&this.status<300)c({blob:l.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},l.onerror=function(){throw new Error("Failed to load blob")},l.send()}let n=r();e.forEach(o=>{i(o.url,o.name,n.waitOn())}),n.endWith(o=>{let a=createDropEvent(o);t.dispatchEvent(a)})}});var FE,Sa,Ly=I(()=>{"use strict";me();W();de();FE=P("drop-file-step-action"),Sa=class extends q{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:i}=this,n=this.getTarget(),o=O.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,i.fileUrls,this.stepActionUtils.testimServicesApi,o,FE),{downloadFileAndFireDropEvent:c}=await Promise.resolve().then(()=>(_y(),Oy)),l=`
274
274
  const getLocatedElement = ${e.getLocatedElementCode};
275
275
  const createDropEvent = ${e.createDropEvent.toString()};
276
276
  const downloadFileAndFireDropEvent = ${c.toString()};
277
277
  return downloadFileAndFireDropEvent.apply(null, arguments)
278
- `;return await this.driver.executeJS(l,n.locatedElement,a)}}});function By(s={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
278
+ `;return await this.driver.executeJS(l,n.locatedElement,a)}}});function My(s={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
279
279
  var input = getLocatedElement(locatedElement);
280
280
  if(input) {
281
281
  function parents(element, _elements) {
@@ -317,7 +317,7 @@ Please make sure the CLI has stable access to the internet. ${Fc()?"(Internal: n
317
317
  input.removeAttribute("disabled");
318
318
  input.focus();
319
319
  }
320
- }`}async function $E(s,e){let t=null;try{t=(await Nc(s)).body}catch(i){if(jE.error("failed to download input-file content",{err:{message:i.message,stack:i.stack,status:i.status}}),i.response)t=i.response.body;else throw i.cause?new Error(i.message):i}let r=`${Fy.tmpdir()}/${e}`;return await Uy.promises.writeFile(r,t),r}function WE(s){return ie(s,e=>$E(e.url,e.name))}function VE(s,e){return e(s)}async function jy(s,e){let t=await WE(s),r=await ie(t,i=>VE(i,e));return Array.isArray(r)&&r.map(i=>i==null?void 0:i.value)}var Fy,Uy,jE,$y=I(()=>{"use strict";Fy=R(require("os"));He();Uy=require("fs");F();W();jE=P("input-file-utils")});function HE(){return`async function downloadAndUpload(locatedElement, fileUrls) {
320
+ }`}async function BE(s,e){let t=null;try{t=(await Oc(s)).body}catch(i){if(UE.error("failed to download input-file content",{err:{message:i.message,stack:i.stack,status:i.status}}),i.response)t=i.response.body;else throw i.cause?new Error(i.message):i}let r=`${Dy.tmpdir()}/${e}`;return await Ny.promises.writeFile(r,t),r}function jE(s){return ie(s,e=>BE(e.url,e.name))}function $E(s,e){return e(s)}async function Fy(s,e){let t=await jE(s),r=await ie(t,i=>$E(i,e));return Array.isArray(r)&&r.map(i=>i==null?void 0:i.value)}var Dy,Ny,UE,Uy=I(()=>{"use strict";Dy=R(require("os"));He();Ny=require("fs");F();W();UE=P("input-file-utils")});function VE(){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;
@@ -394,31 +394,31 @@ Please make sure the CLI has stable access to the internet. ${Fc()?"(Internal: n
394
394
  element.dispatchEvent(new Event("change", { bubbles: true }));
395
395
  }
396
396
  element.removeEventListener("change", changeFiredHandler, true);
397
- }`}var Ia,Ra,Wy=I(()=>{"use strict";$y();me();W();F();de();Ia=P("input-file-step-action"),Ra=class extends q{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){Ia.info("workaround - stepaction - move element to visible position");let i=`
397
+ }`}var Ea,Ia,By=I(()=>{"use strict";Uy();me();W();F();de();Ea=P("input-file-step-action"),Ia=class extends q{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){Ea.info("workaround - stepaction - move element to visible position");let i=`
398
398
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
399
- var getVisibleElement = ${By(r)};
399
+ var getVisibleElement = ${My(r)};
400
400
  return getVisibleElement.apply(null, arguments);
401
- `;return this.driver.executeJS(i,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(i){throw Ia.error("failed to set input file in Safari recovery",{err:i}),i}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(i){let n="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=i?i.message:"";if(f===d||f.startsWith(m)||f.startsWith(n)||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 Ia.error("failed to set input file",{err:i}),i}}async uploadFiles(t,r){for(let i of t)await this.driver.elementIdValue(Fe(r.seleniumElement),i)}async performAction(){let t=this.getTarget(),r=O.flags.overrideAzureStorageUrl.isEnabled(),i=O.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:n,context:o,step:a,stepActionUtils:c,driver:l}=this,d=await n.utils.addTokenToFileUrls(o.project.id,a.fileUrls,c.testimServicesApi,r,Ia);if(d.length===0)throw new Error("No files urls to upload");if(i&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await $t(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(i,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(i){throw Ea.error("failed to set input file in Safari recovery",{err:i}),i}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(i){let n="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=i?i.message:"";if(f===d||f.startsWith(m)||f.startsWith(n)||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 Ea.error("failed to set input file",{err:i}),i}}async uploadFiles(t,r){for(let i of t)await this.driver.elementIdValue(Fe(r.seleniumElement),i)}async performAction(){let t=this.getTarget(),r=O.flags.overrideAzureStorageUrl.isEnabled(),i=O.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:n,context:o,step:a,stepActionUtils:c,driver:l}=this,d=await n.utils.addTokenToFileUrls(o.project.id,a.fileUrls,c.testimServicesApi,r,Ea);if(d.length===0)throw new Error("No files urls to upload");if(i&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await $t(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
- const downloadAndUploadFile = ${HE()};
404
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await jy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var xa,Ca,Vy=I(()=>{"use strict";xa=require("url");me();Ca=class extends q{async updateBaseUrl(e){let t=new xa.URL(e),r=new xa.URL(this.context.recordedBaseUrl),i=new xa.URL(this.context.baseUrl);return t.host===r.host&&r.host!==i.host&&(t.host=i.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 Aa,Gy=I(()=>{"use strict";me();F();Aa=class extends q{async performAction(){await pe(this.step.durationMS||0)}}});var Pa,Hy=I(()=>{"use strict";me();Pa=class extends q{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var rn,qy=I(()=>{"use strict";me();rn=class extends q{async runApiInAut(e){var i;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let n=await this.driver.executeCodeAsync(r,t,e);return(n==null?void 0:n.value)||{}}catch(n){throw(i=n==null?void 0:n.message)!=null&&i.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.'):n}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,i={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},n=t.sendViaWebApp?await this.runApiInAut(i):await this.runApiInBg(i),o=n.result||{},a={method:t.method,status:o.status,url:t.url};return n.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 ka,zy=I(()=>{"use strict";me();ka=class extends q{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 Ky,Zu,ep,Jy=I(()=>{"use strict";Ky=R(require("@applitools/spec-driver-webdriverio"));En();ve();Zu=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=Cd["@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:Ky.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,i){let{EyeSdkBuilder:n}=ee(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return n.rememberCreatedBatch(r,i),o}},ep=new Zu});var Yy,tp,sn,Xy=I(()=>{"use strict";Yy=R(require("lodash"));me();W();Jy();tp=P("pixel-validation-step-action"),sn=class extends q{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:i,testResultId:n}=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)||n,c=await ep.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:i}),g={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};Yy.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),tp.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()},tp.info("Applitools SDK step executed successfully (selenium mode)",{projectId:this.context.projectId})}catch(f){tp.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await ep.handleApplitoolsSdkResult(this.context,d,this.step)}}});var _s,rp=I(()=>{"use strict";xs();X();ha();_s=class extends lr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:n="",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 Rs(n,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 ce?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ur,Qy=I(()=>{"use strict";rp();ur=class extends _s{isFailedResult(e){return e===!1}}});var Oa,Zy=I(()=>{"use strict";rp();Oa=class extends _s{isFailedResult(e){return!e}}});var _a,eb=I(()=>{"use strict";xs();me();X();_a=class extends q{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:i,stepResultId:n,timeToPlayBeforeExec:o}=this.context;try{return{data:await Is(e,r,i,t,n,o),success:!0}}catch(a){return a instanceof Pt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ce?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var jr,tb=I(()=>{"use strict";me();jr=class extends q{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,rb=I(()=>{"use strict";me();be=class extends q{async performAction(){var r,i;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((n,o)=>this.context.playback.sfdcAddLog(n,o)));t.log.info(`BEGIN STEP '${(i=(r=this.step).getStepPreview)==null?void 0:i.call(r)}'`);try{let n=this.context.sfdcTestActions;if(n===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,n,this.context)}}catch(n){return{success:!1,reason:n.reason||n.message,exception:n,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Da,sb=I(()=>{"use strict";me();Da=class extends q{async performAction(){var r,i;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((n,o)=>this.context.playback.sfdcAddLog(n,o)));t.log.info(`BEGIN STEP '${(i=(r=this.step).getStepPreview)==null?void 0:i.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(n){return{success:!1,reason:n.reason||n.message,exception:n,shouldRetry:!1}}finally{t.releaseObjects()}}}});var La,ib=I(()=>{"use strict";me();La=class extends q{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 qE(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Na(s,e){qE(zE,e),e.registerLocateStepActionUtils(Qi.getUtils(s))}var zE,sp=I(()=>{"use strict";ty();iy();my();fy();hy();Ty();Sy();Ey();Iy();Ry();Ay();Py();ky();Dy();My();Wy();Vy();Gy();Hy();qy();zy();Xy();Qy();Zy();eb();tb();rb();sb();ib();zE={locate:Qi,scroll:pa,mouse:da,submit:wa,text:fa,"special-key":ya,"user-code":zt,"validation-code-step":zt,"wait-for-code-step":zt,"action-code-step":zt,"condition-step":Os,"skip-code-step":Os,"element-code-step":Os,"evaluate-expression":ma,"text-validation":en,"wait-for-text-validation":en,"select-option":Ta,"drop-file":Ea,"input-file":Ra,hover:va,navigation:Ca,wheel:Sa,sleep:Aa,refresh:Pa,"keyboard-shortcut-step":ba,"api-validation":rn,"api-action":rn,"api-code-step":zt,"extract-text":ka,"simple-ui-verification":sn,"wait-for-simple-ui-verification":sn,"cli-validation-download-file":jr,"cli-wait-for-download-file":jr,"network-validation-step":jr,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":Oa,"node-package":_a,"email-code-step":zt,"cli-email-code-step":ur,"sfdc-internal-test-step":La,"sfdc-recorded-step":Da,"sfdc-step-login":be,"sfdc-step-loginas":be,"sfdc-step-logout":be,"sfdc-step-sobjectcreate":be,"sfdc-step-sobjectdelete":be,"sfdc-step-findrecord":be,"sfdc-step-quickaction":be,"sfdc-step-sobjectedit":be,"sfdc-step-sobjectvalidate":be,"sfdc-step-launchapp":be,"sfdc-step-wait-for-page-load":be,"sfdc-step-closeconsoletabs":be,"sfdc-step-relatedlistaction":be,"sfdc-step-permission-validation":be,"sfdc-step-convert-lead-to-opportunity":be,"sfdc-step-quotelineeditor":be,"sfdc-document-validation":jr,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var nb,KE,Ds,ip=I(()=>{"use strict";nb=["simple-ui-verification","wait-for-simple-ui-verification"],KE=[...nb,"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"],Ds=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=n=>{let o=this.getTotalStepTimeLeftToPlay(e,n),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),i=KE.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,i),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return nb.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,i=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),i)}}});var ab={};z(ab,{SeleniumTestPlayer:()=>nn});var ob,JE,nn,np=I(()=>{"use strict";F();ob=require("@applitools/eyes-sdk-core");Wi();X();W();zu();Yh();Xu();la();Zh();Qu();ve();sp();ip();oe();JE=P("SeleniumTestPlayer"),nn=class{constructor(e,t,r,i,n=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Ds(ua());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=i??new Dr;let d=new ca(this.driver);this.stepActionFactory=new l(d),Na(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new oa(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Qh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ks(this.driver),FrameLocator:m,portSelector:aa,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:ob.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=n,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,i){i!=null&&i.isTabOpener&&this.tabService.addNewPopup(this.id,i.id).catch(()=>null)}async onDone(){var r,i;let{commonConstants:e}=ee(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(n){n instanceof ce&&await((i=this.driver)==null?void 0:i.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)){JE.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let i=r.at(-1);await this.tabService.addNewTab(this.id,i,e,t),await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let i=await this.driver.getTabIds(),n=[new URL(st||br).hostname].concat(r);for(let o of i.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(n.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 ap={};z(ap,{WorkerSelenium:()=>op});function XE(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Ma,YE,op,cp=I(()=>{"use strict";F();We();Yi();W();Lt();Wo();ae();Hu();X();np();ve();ut();Ma=P("worker-selenium"),YE=1e9,op=class extends Mt{initPlayer(t){return new nn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,i,n){M("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=i;this.windowUtils=new Ps(this.id,o),i.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:n,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:l,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.SELENIUM,customCapabilities:t.customCapabilities}),M("in WorkerSelenium after driver.init"),await i.addTab(void 0,{skipLoadInfo:l}),M("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,YE),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 At||d||m?new At(`Page '${c}' is not available`):(Ma.error("failed to navigate to page",{baseUrl:c,err:l,whitelistedPublicIp:no(),initializedFromCache:oo()}),l)}}async runTestOnce(t,r){var m;let{manifestVersion:i,localAssetService:n}=ee(),{driver:o,sessionPlayer:a}=r,c=i||"runner";Z.onWaitToTestComplete(this.id),XE(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===K.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),n.initialize({serverUrl:this.options.localRCASaver});let l=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(l=(await Hi(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 ce&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await n.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Ma.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&&(Ma.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 Ma.error("failed to run test once",{err:u}),u}}}});var cb,lb,qe,QE,lp,Et,Fa=I(()=>{"use strict";cb=R(require("ora")),lb=require("jimp");oe();He();ge();W();ae();ve();de();qe=P("mobile-grid-service"),QE="https://tdc.tricentis-cloud.com",lp=class{constructor(){this.gridsAppIdGetter={[D.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[D.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[D.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[D.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[D.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return e.type===D.TESTIM_TDC?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===D.TESTIM_TDC?`${r||Ec}/${Wd}/devices`:""}getHeaders(e){return{...e.type===D.TESTIM_TDC&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...e.type===D.TESTIM_TDC&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),i=this.getHeaders(e),n=this.buildRequestBody(e,t);try{await Ge({url:r,headers:i,body:n})}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 i=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let n=await we(i,void 0,this.getHeaders(e));return this.extractTDCDeviceConnection(n,e.accessToken)}catch(n){throw qe.error("error while getting automation config for device",{error:n,deviceId:t}),n}}async getPCloudyAuthToken(e,t,r){let i=await Qs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(i).result.token}extractTDCDeviceConnection(e,t){let r=Object.keys(e)[0],i=e[r].driver_url,n=new URL(i);return{hostname:n.hostname,port:Number(n.port),protocol:n.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return e.type===D.TESTIM_TDC&&(r=await this.getTDCDeviceConnection(e,t)),r}getGridConnection(e){var r;if(e.type===D.TESTIM_TDC){let i=(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:i}}if(e.type===D.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===D.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([D.BROWSERSTACK,D.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:i,companyId:n,gridId:o}){var a,c,l;if(t===D.TESTIM_TDC){let d=await an({projectId:r,projectType:i,companyId:n,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===D.BROWSERSTACK)return((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName);if(t===D.SAUCELABS)return e.testobject_device_name;if(t===D.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,i,n=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=i,h=t.capabilities,g=h.platformName,y;if(f===D.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:b}=ee();y=b(t.capabilities,n)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,d,m,u,n);let v=await this.buildRemoteResultLink(i.gridData,t.sessionId,h);return await kr(l,o,a,c,"RUNNING",{device:y,...v&&{remoteResultLink:v}}),qe.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:y,remoteResultLink:v,gridType:f}),y}getOsVersion(e,t){var i;let r=e.platformVersion;return!r&&t===D.BROWSERSTACK?(i=e.mobile)==null?void 0:i.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,i,n){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,n),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(c,"base64"),m=await lb.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/l.width,width:u,height:f}}catch(o){return qe.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:i==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,i,n,o,a,c,l,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,i,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:n,projectId:o,projectType:a,companyId:c,gridId:l})]),f=this.getOsVersion(e,n);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:i,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===D.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Gs}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===D.SAUCELABS?r.testobject_test_report_url:e.type===D.TESTIM_TVC?r.replayUrl:e.type===D.TESTIM_TDC?`${QE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let i=(await we(`${e}/api/devices`)).find(n=>n.udid===t);if(!i)throw new Error(`device ${t} not found`);return{udid:i.udid,name:i.name,model:i.model,height:i.height,width:i.width,geo:"local",osVersion:i.osVersion,osType:i.deviceType.toLowerCase(),scaleFactor:i.scaleFactor??0,isVirtual:i.virtual??!1,minApiVersion:i.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:i,testId:n,testResultId:o}=r,{project:a,localTmaUrl:c}=t,l=await this.getTmaDeviceDetails(c,e);return await kr(a,i,n,o,"RUNNING",{device:l}),qe.info("device details updated on testResult",{testResultId:o,executionId:i,testId:n,device:l}),l}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let i=e.type,n=t.mobileApp,o=this.gridsAppIdGetter[i]({testRunHandler:t,mobileApp:n,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 pp({gridAppId:o,gridId:e.gridId,projectId:r,gridType:i,appId:n.appId,gridHost:e.host})),o):t.getAppPathByGridType(i,e.gridId,n)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let i=await on({appId:e,projectId:t});return{appUrl:`${he()}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/($d*60))+1)*60*1e3,Math.max(jd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:i,gridType:n}){let a={[D.BROWSERSTACK]:{name:"Browserstack"},[D.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[D.P_CLOUDY]:{name:"pCloudy"}}[n].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,cb.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 up({projectId:e,gridId:i,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:i,gridType:n,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:i,gridType:n});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let i="",n,{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 i;if(c){qe.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let v=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:d});i=v.appUrl,n=v.mobileApp,e.nativeApp=n}else qe.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:o}),i=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:m,testRunHandler:e}),y=f===D.BROWSERSTACK||f===D.TESTIM_TVC||f===D.P_CLOUDY;if(g){let v=t.projectData.type,b=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:v});b&&(qe.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),i=g),!b&&y&&(qe.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),i=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!b&&!y&&qe.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&y&&(i=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),i}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:i,user:n,host:o,key:a,type:c,apiUrl:l}=t;if(c===D.BROWSERSTACK){let u=`${Gs}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:n,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(c===D.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:n,key:a})).items.some(h=>h.id===e)}if(c===D.TESTIM_TDC){let u=`${l}/${Ic}/apps`;return l||(u=`${Ec}/${Ic}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:i,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(c===D.TESTIM_TVC){let u=`${Vd}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&qe.error("error while verifying app exists on TVC",{error:h}),!1}}if(c===D.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,n,a),f=`https://${o}/api/drive`,h=await Dc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let i={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await we(e,void 0,i)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:i}){let n={Authorization:`${r} ${t}`,...i&&{"User-Agent":i}};return await we(e,void 0,n)}},Et=new lp});function ub({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"&&!ZE.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!==D.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 tI(s){let{testName:e,executionId:t,testResultId:r,customTag:i}=s,n=[{executionId:t},{testResultId:r}];return e&&n.push({testName:e}),i&&n.push({customTag:i}),n}function rI(s,e,t,r){let{fullReset:i,setNoReset:n,skipLoadBalancer:o}=e,c=s===D.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"]:tI(t),["tdc:enableBatch"]:c,...!i&&{"appium:noReset":n},...l&&{["tdc:newCommandTimeout"]:600,"appium:newCommandTimeout":600},...r}}function Ua(s){return"id"in s?s.id:s.packageName}function sI(s){return{"tdc:app.id":s}}function iI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:i,androidActivityWait:n}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":i},l=i==null?void 0:i.startsWith("http");i&&!l&&(c=sI(i));let m=()=>o===void 0&&i?!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":Ua(r)},...i&&c};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...n&&{"appium:appWaitActivity":`${n}, *`},...r&&{"appium:appPackage":Ua(r),"appium:appActivity":r.activity??".*"},...i&&c};default:throw Error(`unsupported mobile project ${s}`)}}function Wr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,appiumPrefix:n="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${n}autoAcceptAlerts`]:!0,[`${n}automationName`]:o?"WaldoTestim":"XCUITest",[`${n}fullReset`]:!0,...t&&{[`${n}bundleId`]:Ua(t)},...r&&{[`${n}app`]:r},...e};case"android":return{platformName:"Android",[`${n}autoGrantPermissions`]:!0,[`${n}automationName`]:o?"WaldoTestim":"UiAutomator2",...i&&{[`${n}appWaitActivity`]:`${i}, *`},...t&&{[`${n}appPackage`]:Ua(t),[`${n}appActivity`]:t.activity??".*"},...r&&{[`${n}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function pb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:i,options:n,gridInfo:o,shouldRunInEnhancedMode:a,customCapabilities:c}){let l=rI(o.type,n,i,c);return iI({projectType:s,sessionCaps:l,options:n,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Ba({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 ja({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:i,dynamicAllocation:n}=e,o=r===D.P_CLOUDY;return s||(i!=null&&i.deviceName?o?i.deviceUdid:i.deviceName:n!=null&&n.deviceNameRegex?t==="android"&&n.deviceNameRegex===".*"&&o?Rc:n.deviceNameRegex:t==="ios"&&r===D.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":Rc:".*")}function nI(s,e){let{androidToken:t,iosToken:r}=s,i=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(i&&!r)throw Error("missing ios token for testim virtual cloud");if(!i&&!t)throw Error("missing android token for testim virtual cloud");return i?r:t}function oI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...$r(s,pr)}}function db(s,e,t){return s?Object.entries(s).reduce((r,[i,n])=>{if(e(i)){if(!t)return r[i]=n,r;let o=i.replace(t,"");r[o]=n}return r},{}):{}}function aI(s){return db(s,e=>e.startsWith("browserstack."),"browserstack.")}function cI(s){return db(s,e=>!e.startsWith("browserstack."))}function mb(s){return!s||!fb(s)?"2.0.0":s}function fb(s){return s.split(".")[0]==="2"||s.includes("appium2")||["latest","stable"].includes(s)}function gb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let i=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,n=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&n.test(s),c=e==="android"&&(i.test(s)||a),l=e==="ios"&&o.test(s),d=c||l;if(t){let m=fb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function $r(s,e){let t={};return Object.entries(s).forEach(([r,i])=>{let n=r.startsWith(e)?r:`${e}${r}`;t[n]=i}),t}async function lI(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,options:n,gridInfo:o,sessionTags:a,testRunConfig:c,shouldRunInEnhancedMode:l,customCapabilities:d}=s,{osVersion:m,deviceName:u}=n,f=(c==null?void 0:c.mobile)||{},{type:h}=o,g=nI(o,e),y=await an({gridId:o.gridId,projectType:e,projectId:n.project,companyId:n.company.companyId}),v=y==null?void 0:y.find(({udid:C})=>{var _;return((_=f.staticAllocation)==null?void 0:_.deviceUdid)===C}),b=(v==null?void 0:v.osVersion)??Ba({osVersion:m,mobileConfig:f}),T=(v==null?void 0:v.name)??ja({deviceName:u,mobileConfig:f,projectType:e,gridType:h}),w=Ke(n.editorUrl,n.project,a.testId,a.testResultId,a.branch),E={device:T,os_version:b,"waldo:displayName":`${a.testName}-${a.executionId}-${a.testResultId}`,"waldo:externalUrl":w,...l&&{"waldo:automationName":"WaldoTestim"},...d};return E["waldo:options"]||(E["waldo:options"]={}),E["waldo:options"].token||(E["waldo:options"].token=g),Wr({projectType:e,sessionCaps:E,nativeAppMetadata:t,appPath:r,androidActivityWait:i,shouldRunInEnhancedMode:l})}function uI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:i,gridInfo:n,sessionTags:o,testRunConfig:a,customCapabilities:c}){let{osVersion:l,deviceName:d}=i,m=(a==null?void 0:a.mobile)||{},{user:u,key:f,type:h}=n,g=O.flags.enableAppium2pCloudy.isEnabled(),y=Ba({osVersion:l,mobileConfig:m}),v=ja({deviceName:d,mobileConfig:m,projectType:s,gridType:h}),b=/^[a-zA-Z]+$/.test(v),T={...y!==".*"&&{pCloudy_DeviceVersion:y},...b&&{pCloudy_DeviceManufacturer:v},...!b&&{pCloudy_DeviceFullName:v}},w={pCloudy_Username:u,pCloudy_ApiKey:f,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...T,pCloudy_DurationInMinutes:i.duration?Number(i.duration):Number(Gd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5,...c};return g&&(w=oI(w)),t="",Wr({projectType:s,sessionCaps:w,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...g&&{appiumPrefix:pr}})}function pI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:i,gridInfo:n,sessionTags:o,testRunConfig:a,customCapabilities:c}){let{osVersion:l,deviceName:d}=i,m=(a==null?void 0:a.mobile)||{},{type:u}=n,f=Ba({osVersion:l,mobileConfig:m}),h=ja({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),g=(0,It.omit)({...i.saucelabs},["automationName","platformName"]),y={...g["sauce:options"]};delete g["sauce:options"];let v={...c==null?void 0:c["sauce:options"]},b=(0,It.omit)(c,"sauce:options"),T=y.appiumVersion||v.appiumVersion,w=g.platformVersion||b.platformVersion||f;if(gb({osVersion:w,projectType:s,appiumVersion:T})){let C={debug:!0,networkLogs:!0},_={user:n.user,key:n.key,name:o.testResultId,build:o.executionId,appiumVersion:mb(T??"stable"),deviceName:h,tags:Object.values(o)},B={"appium:platformVersion":f,"appium:deviceName":h,...$r(g,pr),...$r(b,pr),"sauce:options":{...C,..._,...(0,It.omit)(y,"appiumVersion"),...(0,It.omit)(v,"appiumVersion")}};return Wr({projectType:s,sessionCaps:B,appiumPrefix:pr,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let E={"saucelabs.user":n.user,"saucelabs.key":n.key,platformVersion:f,deviceName:h,tags:Object.values(o),name:o.testResultId,build:o.executionId,...g,...y,...b,...v};return Wr({projectType:s,sessionCaps:E,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function dI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,options:n,gridInfo:o,sessionTags:a,testRunConfig:c,customCapabilities:l}){let{osVersion:d,deviceName:m}=n,u=(c==null?void 0:c.mobile)||{},{type:f}=o,h=Ba({osVersion:d,mobileConfig:u}),g=ja({deviceName:m,mobileConfig:u,projectType:e,gridType:f}),y=aI(n.browserstack),v=(0,It.omit)(cI(n.browserstack),["automationName","platformName","project","build","name"]),b={...l==null?void 0:l["bstack:options"]},T=(0,It.omit)(l,"bstack:options"),w=y.appiumVersion||b.appiumVersion,E=v.platformVersion||T.platformVersion||h,C=O.flags.enableAppium2BrowserStack.isEnabled(),_={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`};if(C||gb({osVersion:E,projectType:e,isBrowserStack:!0,appiumVersion:w})){let V={..._,userName:o.user,accessKey:o.key,appiumVersion:C?"2.0.1":mb(w),debug:!0,networkLogs:!0},S={"appium:platformVersion":h,"appium:deviceName":g,...$r(v,pr),...$r(T,pr),"bstack:options":{...V,...(0,It.omit)(y,"appiumVersion"),...(0,It.omit)(b,"appiumVersion")}};return Wr({projectType:e,sessionCaps:S,appiumPrefix:pr,nativeAppMetadata:t,appPath:r,androidActivityWait:i})}let B={..._,os_version:v.platformVersion||h,device:v.deviceName||g,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...v,...$r(y,"browserstack."),...T,...$r(b,"browserstack.")};return Wr({projectType:e,sessionCaps:B,nativeAppMetadata:t,appPath:r,androidActivityWait:i})}async function mI(s){if(D.TESTIM_TDC===s.gridInfo.type)return pb(s);if(D.TESTIM_TVC===s.gridInfo.type)return await lI(s);if(D.P_CLOUDY===s.gridInfo.type)return uI(s);if(D.SAUCELABS===s.gridInfo.type)return pI(s);if(D.BROWSERSTACK===s.gridInfo.type)return dI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function fI(s,e){var l,d;let{staticAllocation:t,dynamicAllocation:r,type:i}=e||{},{deviceName:n,osVersion:o,deviceUdid:a}=s,c={};return i==="dynamic"&&(!n&&((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)),i==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),n&&(c.manufacturer=n),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function hb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:i,testRunConfig:n}=s,{selectedGrid:o}=(n==null?void 0:n.mobile)||{};if(n!=null&&n.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);ub({nativeAppMetadata:t,appPath:i,gridInfo:e});let a=Et.getGridConnection(e),c=await mI(s);if(e.type===D.TESTIM_TDC){let y=fI(r,n==null?void 0:n.mobile);if(!(0,It.isEmpty)(y)){let v=Object.entries(y).map(([b,T])=>T.split(",").map(w=>w===".*"||w==="="?"":`${b}:${w}`).join(",")).join(" ").trim();c["tdc:selector"]=v}}let l=e.type===D.TESTIM_TVC?{alwaysMatch:c}:c,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,dp.default)("2m"),f=(0,dp.default)("12m"),h=vr(O.flags.appiumConnectionRetryCount.getValue(),m),g=vr(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 yb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:i,appPath:n,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=i;ub({nativeAppMetadata:r,appPath:n,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 Et.getGridDirectConnection(t,d),f=pb({projectType:e,nativeAppMetadata:r,appPath:n,androidActivityWait:o,options:i,sessionTags:a,testRunConfig:c,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:i.appiumLogLevel}}function bb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,customCapabilities:n}=s,o={...n,dontStopAppOnReset:!0,fullReset:!1},a=Wr({projectType:e,sessionCaps:o,nativeAppMetadata:t,appPath:r,androidActivityWait:i});return e==="ios"&&delete a.app,a}function Tb(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 dp,It,pr,ZE,mp=I(()=>{"use strict";dp=R(require("ms"));de();ae();Fa();It=require("lodash");F();oe();ge();pr="appium:",ZE=[D.BROWSERSTACK,D.SAUCELABS,D.TESTIM_TDC,D.TESTIM_TVC,D.P_CLOUDY]});var $a,vb=I(()=>{"use strict";$a=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Wa,Sb=I(()=>{"use strict";F();Wa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=ni;this.getLinksFromUnescapeHTML=oi}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var fp,Va,Eb=I(()=>{"use strict";W();fp=P("mobile-frame-locator-mock"),Va=class{foundFrameCallback(){return fp.info("foundFrameCallback-mock invoked"),{}}locate(){return fp.info("locate-mock invoked"),{}}async findFrame(){return fp.info("findFrame-mock invoked"),{}}}});var gI,Rb,Ib,Ls,gp=I(()=>{"use strict";gI=R(require("webdriverio")),Rb=require("@applitools/eyes-sdk-core");vb();Xu();W();Sb();Qu();ve();sp();Eb();ip();Ib=P("appium-test-player"),Ls=class{constructor(e,t,r,i=gI,n=void 0,o=void 0){this.id=e;this.driver=i;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=ee(),m=new Wa(this.driver);this.stepActionFactory=new l(m),Na(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ds(ua()),this.sessionPlayer=new a(e,{tabService:new $a,cookieUtils:void 0,FrameLocator:Va,portSelector:aa,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Rb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=n,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,i){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:i}=e,n={executionId:t,testResultId:r,sessionId:i==null?void 0:i.sessionId};try{i!=null&&i.sessionId&&(await(i==null?void 0:i.endSession()),Ib.info("appium session deleted",{...n}))}catch(o){Ib.error("error while deleting appium session",{...n,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 hI(s){return await we(`${s}/api/status`)}async function xb(s,e){return await we(`${s}/api/devices/${e}/status`)}async function Cb(s){if((await hI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Ab=I(()=>{"use strict";He()});var Pb={};z(Pb,{WorkerLocalTma:()=>Tp});var Vr,hp,yp,bp,Tp,kb=I(()=>{"use strict";He();mp();Yi();F();W();Lt();gp();ve();Ab();Fa();Vr=P("worker-appium"),hp=class extends Error{},yp=class extends Error{},bp=class extends Error{},Tp=class extends Mt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Ls(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:i}=await import("linkedom"),n=new r(this.sessionData.serverAddress,this.sessionData.sessionId,i,!1);return t.sessionPlayer.playbackManager.appiumApi=n,n}async getBrowserOnce(t,r,i,n){var E;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 Cb(o);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=i,u=c.type,f=this.options.appId;if(f){let{mobileApp:C}=await Et.getMobileAppDataByAppId({appId:f,projectId:l,token:d});t.nativeApp=C}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,v=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!v)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:b,version:T},w]=await Promise.all([this.getAppStateFromDevice(o,a,v),xb(o,a)]).catch(C=>{throw this.handleDeviceNotFoundError(C),C});if(Vr.info("device status and app state",{deviceStatus:w,appInstalled:b,version:T,executionId:this.executionId,testResultId:this.testResultId}),!b&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!b&&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:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},_=bb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:C,gridInfo:n,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 V=await this.requestNewAppiumSessionFromTma(o,B,g);this.sessionData=V;let S=await m.attach({sessionId:V.sessionId,capabilities:_,options:{capabilities:_}});this.device=await Et.updateTmaDeviceDetails(a,this.options,t),Vr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:S.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:S.capabilities})}catch(C){throw Vr.error("failed to start application",{err:C}),C}}async requestNewAppiumSessionFromTma(t,r,i){var n,o;try{let a=await Ge({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:i.name,version:i.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(n=a.response)==null?void 0:n.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new bp(c):a}}async getAppStateFromDevice(t,r,i){let n=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${n}`,c=(await we(o)).find(l=>"id"in l?l.id===i:l.packageName===i);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,i){var n,o;try{let a=await $t(i);await Xs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(n=a.response)==null?void 0:n.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new yp(l,{cause:a})}}handleDeviceNotFoundError(t){var i,n;let r=(n=(i=t.response)==null?void 0:i.body)==null?void 0:n.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new hp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:i,localAssetService:n}=ee(),{sessionPlayer:o}=r,a=i||"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),n.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 n.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 _b={};z(_b,{WorkerAppium:()=>wp});var Ob,Gr,wp,Db=I(()=>{"use strict";F();mp();Ob=require("linkedom");Yi();W();Lt();gp();ve();Fa();ae();gs();Gr=P("worker-appium"),wp=class extends Mt{initPlayer(t){return new Ls(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,i,n){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(n.type!==D.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}=i,l=await Et.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,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectData:this.options.projectData,projectType:o,nativeAppMetadata:m,appPath:l,androidActivityWait:d,sessionTags:u,gridInfo:n,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a,customCapabilities:t.customCapabilities},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Et.lockDevice(n,this.options.deviceUdid),h=await yb(f)):h=await hb(f),Gr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:Tb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await c.remote(h),this.device=await Et.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(),i=async()=>{try{await t.getOrientation()}catch(n){Gr.error("failed to keep appium session alive",{err:n}),r!=null&&r.AppiumSessionTerminatedError&&n instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(i,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&Qf(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:i,type:n}=this.options.gridData;return n===D.TESTIM_TDC?`https://${t}:${r}/v0/${i}/wd/hub`:n===D.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:i,path:n}=this.activeSession.options;if(t&&r&&i&&n)return`${t}://${r}:${i}${n}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:i,AppiumApi:n,localAssetService:o}=ee(),{sessionPlayer:a}=r,c=i||"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:v,hostname:b,port:T,path:w}=await Et.getTDCDeviceConnection(this.options.gridData,y);d=`${v}://${b}:${T}${w}`}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 n(d,this.activeSession.sessionId,Ob.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((b,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:b,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});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 Ga,Lb=I(()=>{"use strict";F();Wi();X();Ga=class{constructor(e){this.id=e;this.driver=new Dr}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof ce&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function Nb(){let s=await Promise.any(yI.map(async e=>{try{return await we(e)}catch{return null}}));return s==null?void 0:s.ip}var yI,Ha,qa=I(()=>{"use strict";He();yI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];Ha=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var Mb,za,Fb=I(()=>{"use strict";Mb=R(require("ws"));F();qa();za=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=Ha({timeout:e}),r=new Mb.default(this._cdpUrl,t),i=Qt(o=>{r.once("open",o)}),n=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([i,n]).then(()=>r),this._cdpWs}onCDPMessage(e){var i;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)):(i=t.result.exceptionDetails)!=null&&i.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 i=await this.initCDPWebsocket();this._lastWsId||=0;let n=this._lastWsId++,o=new Promise((c,l)=>{this._cdpCallbacks.set(n,{resolve:c,reject:l})}),a={method:e,params:t,id:n};return r&&Object.assign(a,{sessionId:r}),i.send(JSON.stringify(a)),o}}});var Ja,vp,Ka,Ub=I(()=>{"use strict";F();Ja=R(require("chrome-launcher"));Uo();Fb();ki();vp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new za}async init(e){var h,g,y,v;let{browserOptions:t,testName:r,testRunConfig:i,gridInfo:n,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}=e,m=Fo({browserOptions:t,testName:r,testRunConfig:i,gridInfo:n,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((v=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:v.args)??[],...Ja.Launcher.defaultFlags().filter(b=>b!=="--disable-extensions")];this.chrome=await Ja.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await Er(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),hs(()=>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}},Ka=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new vp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Sp={};z(Sp,{WorkerExtension:()=>cn});function bI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Bb(s){return bI(s)?s:new Error(s)}var tt,cn,Ya=I(()=>{"use strict";We();X();Yi();F();W();Lt();ae();Lb();Ub();ut();tt=P("worker-ext"),cn=class extends Mt{initPlayer(){return this.options.useChromeLauncher?new Ka(this.id):new Ga(this.id)}async _getBrowserOnce(e,t,r,i){var o;let{driver:n}=r;try{return await n.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,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:K.EXTENSION})}catch(a){throw tt.error("failed to get browser",{err:a,gridInfo:i,whitelistedPublicIp:no(),initializedFromCache:oo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,i){return Z.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,i)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var n;let i=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${i}`),"browserstack"in this.options&&((n=this.options.browserstack)!=null&&n["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:i,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:i,testId:n}=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 ce))throw u;return tt.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 tt.error("error from driver.url",{err:f,testResultId:r,executionId:i,testId:n,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 tt.warn("failed to run test via CDP",{err:y}),y}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let b=function(w){e.onCompletedCleanup(),tt.warn("on browser closed error detected",{err:w,testResultId:r,executionId:i,testId:n}),m.unregisterToClosedBrowser(b),m.unregisterToKeepAliveFailed(T),w.type=Xr.BROWSER_CLOSED,v.abort(w)},T=function(w){m.unregisterToClosedBrowser(b),m.unregisterToKeepAliveFailed(T),tt.warn("on keep alive failed error detected",{err:w,testResultId:r,executionId:i,testId:n}),w.type=Xr.KEEP_ALIVE_FAILED,v.abort(w)};var f=b,h=T;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(w){if(!(w instanceof ce))throw w;tt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:i,testId:n,...u}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let v=new AbortController;m.registerToClosedBrowser(b),m.registerToKeepAliveFailed(T);try{let w=le(e.onCompleted(),this.testRunTimeout,Pe.TEST_COMPLETE_TIMEOUT_MSG),E=await Pc(w,v.signal);m.unregisterToClosedBrowser(b),m.unregisterToKeepAliveFailed(T);try{await this.updateTestStatusOnGrid(m,Boolean(E.success),E.reason)}catch(B){tt.error("Could not update the grid about the test status",{err:B})}m.isAlive()||(tt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),E.gridIssues="could not validate grid is alive");let C=m.maxKeepAliveGap();return C>=3e4&&(tt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),E.keepAliveIssue=C),{...E,...e.seleniumPerfStats.getStats()}}catch(w){throw tt.warn("timeout wait until test completed",{err:w,testResultId:r,executionId:i,testId:n}),Bb(w)}finally{m.unregisterToClosedBrowser(b),m.unregisterToKeepAliveFailed(T)}}catch(y){throw tt.warn("failed to start url",{err:y}),Bb(y)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await l()}catch(d){throw tt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Ip={};z(Ip,{WorkerExtensionSingleBrowser:()=>Ep});var TI,wI,Ep,Rp=I(()=>{"use strict";We();F();W();Wu();Lt();Ya();TI=P("base-worker"),wI=500,Ep=class extends cn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Ji(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,i,n){return Z.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,i,n)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(TI.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,i){let n=this.handleQuarantine(t);if(n)return n;M("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,i,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 pe(wI)}}});var xp,Xa,jb=I(()=>{"use strict";Wi();oe();We();kl();ut();Eu();X();W();ae();Dh();Jo();xp=P("worker-manager"),Xa=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 i=this.workerUniqueIds[t%this.parallelCount],n=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,n),n.id=t,n.uniqueId=i,n.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case K.SELENIUM:return(await Promise.resolve().then(()=>(cp(),ap))).WorkerSelenium;case K.APPIUM:return t?(await Promise.resolve().then(()=>(kb(),Pb))).WorkerLocalTma:(await Promise.resolve().then(()=>(Db(),_b))).WorkerAppium;default:return Vi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Rp(),Ip))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Ya(),Sp))).WorkerExtension}else switch(r){case(Fr.find(i=>i===r)&&Vi.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Rp(),Ip))).WorkerExtensionSingleBrowser;case Fr.find(i=>i===r):return(await Promise.resolve().then(()=>(Ya(),Sp))).WorkerExtension;case Ki.find(i=>i===r):return(await Promise.resolve().then(()=>(cp(),ap))).WorkerSelenium;default:throw new x(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],i=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return M("before new Worker",r.mode),new i(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,i,n,o,a,c){if(e&&e.length===0)return;let l=!1,d=0,m=(u,f)=>new Promise(h=>{var J,xe,Te,gr,k,L,$,Y;let g=n.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Ko(r,i,e,n,o,t),this.combinedTestResults={};let v=((J=n.company)==null?void 0:J.ucid)||"",b=(xe=n.company)==null?void 0:xe.companyId,T=(Te=n.company)==null?void 0:Te.name,w=n.source||"cli",E=n.user,C=(gr=n.company)==null?void 0:gr.planType,_=(k=n.company)==null?void 0:k.isStartUp,B=(L=n.projectData)==null?void 0:L.name,V=($=n.projectData)==null?void 0:$.type,S=n.lightweightMode,A=(Y=n.gridData)==null?void 0:Y.type,N=(Le,Ct,Se,gc,fn,hc)=>(d++,Nf({executionId:r,projectId:g,testId:Ct,resultId:Se,ucid:v,companyId:b,companyName:T,projectName:B,companyPlan:C,source:w,user:E,lightweightMode:S,isStartUp:_,projectType:V,appSource:hc,gridType:A}),t.testStartAndReport(Le,r,Se,gc,fn)),j=async(Le,Ct,Se,gc,fn,hc)=>{var vd,Sd,Ed;d--;let rt={...(S==null?void 0:S.onlyTestIdsNoSuite)&&{show:!0},...Se.seleniumStats&&{seleniumStats:Se.seleniumStats},...Se.gridIssues&&{gridIssues:Se.gridIssues},...Se.keepAliveIssue&&{keepAliveIssue:Se.keepAliveIssue},...n.host&&{gridHost:n.host}};if(Se.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(Se.seleniumPerfMarks),delete Se.seleniumPerfMarks),n.grid||n.gridId?(rt.gridName=n.grid||((vd=n.gridData)==null?void 0:vd.name),rt.gridType=(Sd=n.gridData)==null?void 0:Sd.type,rt.gridProvider=(Ed=n.gridData)==null?void 0:Ed.provider):n.localTmaUrl?(rt.gridName="local-tma-from-options",rt.gridType="local-tma"):n.useLocalChromeDriver?(rt.gridName="local-chrome-driver-from-options",rt.gridType="local-chrome"):n.useChromeLauncher?(rt.gridName="chrome-launcher-from-options",rt.gridType="local-chrome"):n.browserstack?rt.gridName="browserstack-from-options":n.saucelabs&&(rt.gridName="saucelabs-from-options"),await t.testEndAndReport(Le,Se,r,gc,fn,rt).catch(tw=>xp.error("testEndAndReport threw an error",{err:tw})),fn)return;this.combinedTestResults[Se.resultId]=Se,Mf({executionId:r,projectId:g,testId:Ct,resultId:Se.resultId,result:Se,ucid:v,companyId:b,companyName:T,projectName:B,companyPlan:C,source:w,user:E,lightweightMode:S,logger:xp,isStartUp:_,projectType:V,appSource:hc}),c&&!Se.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},H=(Le,Ct)=>{this.combinedTestResults[Ct.resultId]=Ct,t.onTestIgnored(Le,Ct.resultId),d--,(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},G=(Le,Ct)=>t.onGridSlot(Le,Ct);for(n.userData={loginData:{...Cr(),refreshToken:so(),authData:Cr(),token:u,userAccessKey:f},projectId:n.project,company:n.company,servicesUrl:he()},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(n,this.customExtensionLocalLocation,r,N,j,G,H)});try{let u=await _t(),f=await io(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),l)throw new Yt;return h}catch(u){throw xp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var ln,$b,Qa,Cp,Ap,Hr,Pp=I(()=>{"use strict";ln=R(require("lodash"));F();W();oe();ae();We();ls();Pl();kl();ge();$b=require("uuid");Bf();F();Lt();Eg();X();jb();de();Jo();({CLI_MODE:Qa}=Wt),Cp=P("test-plan-runner"),Ap=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return Ap._id}async runTestAllPhases(e,t,r,i,n,o,a,c){let l={},d=new Xa(this.customExtensionLocalLocation),m=async()=>{let g=n.beforeParallel||1,y=!0,v=await d.runTests(e,c,o,a,n,i,g,y);Object.assign(l,v)},u=async()=>{let g=xn||n.parallel,y=!1;M("right before this.workerManager.runTests");let v=await d.runTests(t,c,o,a,n,i,g,y);M("right after this.workerManager.runTests"),Object.assign(l,v)},f=async()=>{let g=n.afterParallel||1,y=!1,v=await d.runTests(r,c,o,a,n,i,g,y);Object.assign(l,v)};Ff({executionId:o,projectId:n.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(Cp.error("error running test plan",{err:g}),g instanceof Yt)return c.markAllQueuedTests(o,fe.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,v,b,T;if((y=n.lightweightMode)!=null&&y.disablePixelValidation)return;if(n.mode===Qa.SELENIUM){let[{getSessionPlayer:w},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(ve(),or)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=w();await C.closeBatch(o,E);return}let g;try{if(!((T=(b=(v=n.company)==null?void 0:v.activePlan)==null?void 0:b.premiumFeatures)!=null&&T.applitools)||(g=await Dp(n.project),ln.default.isEmpty(g)||!o))return;let{runKey:w,url:E}=g,C=require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}),_=1e4;await le(C.closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:w}}),_)}catch{}}}async runTestPlan(e,t,r,i,n,o,a,c){var T,w,E;let l=se(),d=i.project;rm(l),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Co(m,i,o,a),f=ln.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=(T=i.lightweightMode)!=null&&T.onlyTestIdsNoSuite?[]:m.map(C=>C.name),y=(w=i.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,d,this.startTime,n,g);M("before testListInfoPromise");let v=await y;(E=i.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Z.onTestPlanStarted(v.beforeTests,v.tests,v.afterTests,n,l,c,h),M("before runTestAllPhases");let b=await this.runTestAllPhases(v.beforeTests,v.tests,v.afterTests,a,i,l,n||"All Tests",u);return M("before executionEnd"),await u.executionEnd(l),M("after executionEnd"),{results:b,executionId:l,testPlanName:n,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(ue.colorString(ue.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await kp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await Op(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){Cp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return ln.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let i={},n={},o=e.project,a={testPlans:[],testPlansData:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await ie(e.testPlanIds,async d=>{let m=await un(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await ie(e.testPlan,async d=>{let m=await un(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await un(o,e.testPlan,e.testPlanIds,t,e.intersections);let 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!==Qa.APPIUM&&await ju(e,r(l)),await ie(c,async d=>{var h;let m=d.testPlanId;i[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 Ef(e,d);let f=u.overrideExecutionName||d.name;return await ie(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),i[m][y.executionId]=y.results;let v=Object.keys(i[m]).map(E=>({executionId:E,status:Bu(i[m][E])})),b=Object.keys(i[m]).map(E=>i[m][E]).reduce((E,C)=>Object.assign(E,C),{}),T=Bu(b);Object.assign(n,b);let w=T?v[0].executionId:v.find(E=>!E.status).executionId;return await _p(o,m,{success:T,executions:v,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var c;Cp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await Nh(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 i=r;if(e.rerunFailedByRunId&&!i.runName){if(!i.runExists)throw new x("Invalid run ID - no such run.");i.runName===""&&(i.runName=`rerun-${e.rerunFailedByRunId}`)}let n=e.overrideExecutionName||i.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===Qa.APPIUM&&(a=await on({appId:e.appId,projectId:e.project})),await ie(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!==Qa.APPIUM&&await ju(e,l),M("right before runTestPlan");let d=await this.runTestPlan([],l,[],e,n,null,t,o);return M("right after runTestPlan"),await Z.onTestPlanFinished(d.results,n,this.startTime,d.executionId,o),d})}async run(e){let t=Si(),r=[];await this.reportTestRunnerStarted(e.project,e),ri(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let i=ln.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(i),M("right after onAllTestPlansFinished"),i.map(n=>n.results).reduce((n,o)=>Object.assign(n,o),{})}},Hr=Ap;Hr._id=(0,$b.v4)()});var ke={};z(ke,{addTestRetry:()=>lu,clearTestResult:()=>Fu,deleteCloudflareTunnel:()=>Wp,fetchLambdatestConfig:()=>du,fixGridAppIDStructure:()=>pp,forceUpdateCloudflareTunnelRoutes:()=>$p,getAllGrids:()=>Al,getAppDetails:()=>on,getApplitoolsIntegrationData:()=>Dp,getBrowserStackSessionMetaData:()=>kI,getCloudflareTunnel:()=>jp,getCustomCapabilitiesByName:()=>Gp,getEditorUrl:()=>CI,getFileUrl:()=>Mp,getGridSlot:()=>Cl,getHybridGridProvider:()=>xl,getLabFeaturesByProjectId:()=>Iu,getMobileDevicesFromGrid:()=>an,getRealData:()=>ru,getS3Artifact:()=>Di,getS3ArtifactText:()=>tu,getSuiteTestList:()=>$u,getTestPlan:()=>xI,getTestPlanTestList:()=>un,getTestResults:()=>Mr,getUsageForCurrentBillingPeriod:()=>Up,initializeUserWithAuth:()=>Bp,isTestResultCompleted:()=>Mu,keepAliveCompanySlots:()=>Zl,keepAliveGrid:()=>Il,loadSfdcCredential:()=>Fp,loadTest:()=>qi,releaseCompanySlot:()=>Xl,releaseGridSlot:()=>Rl,reportExecutionFinished:()=>Ao,reportExecutionStarted:()=>cu,reportRunnerFinished:()=>Op,reportRunnerStarted:()=>kp,requestCompanySlot:()=>Yl,saveRemoteStep:()=>xu,saveTestPlanResult:()=>_p,updateCompanySlot:()=>Ql,updateExecutionTests:()=>au,updateRemoteRunFailure:()=>Vp,updateTestDataArtifact:()=>Po,updateTestResult:()=>ta,updateTestStatus:()=>kr,uploadAppToGrid:()=>up,uploadRunDataArtifact:()=>Uu,validateUserAccessKey:()=>Sl});async function Ns(){let s=await _t();if(!s)throw new Error("Failed to get token from server");return{[qc]:Hr.id,Authorization:`Bearer ${s}`}}async function Ce({url:s,body:e,headers:t={},timeout:r,retry:i}){let n=await Ns(),o={...t,...n};return Ge({url:`${he()}${s||""}`,body:e,headers:o,timeout:r,retry:i})}async function II(s,e,t,r={},i=void 0){let n=await Ns(),o={...r,...n};return await Xs(`${he()}${s||""}`,e,t,o,i)}async function pn(s,e){let t=await Ns();return await Lc(`${he()}${s||""}`,e,t)}async function Vb(s,e){let t=await Ns();return await Ys(`${he()}${s||""}`,e,t)}async function RI(s,e){let t=await Ns();return await Qs(`${he()}${s||""}`,e||void 0,t)}async function Re(s,e,t,r){let i=await Ns();return await we(`${he()}${s||""}`,e||void 0,i,r,t)}function Di(s,e){return(0,te.default)(()=>Re(`/storage${s}`,null,{isBinary:!0},e),{retries:re,factor:1})}function Mp(s,e){return(0,te.default)(()=>Re(`/files/fileUrl?${s}`,null,{isBinary:!0},e),{retries:re,factor:1})}function tu(s){return(0,te.default)(()=>RI(`/storage${s}`))}async function kp(s,e){return await Ce({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function Op(s){return await Vb("/test-runner",{projectId:s})}async function xI(s,e){let t=i=>i===null?[]:typeof i=="string"&&JSON.parse(i)||i;return(await(0,te.default)(()=>Re("/testPlan",{projectId:s,name:e.join(",")}),{retries:re,factor:1})).map(({testConfigIds:i,beforeAllLabels:n,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(i),beforeAllLabels:t(n),testLabels:t(o),afterAllLabels:t(a)}))}async function Fp({branch:s,projectId:e}){let t=await(0,te.default)(()=>Re(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:re,factor:1});return t==null?void 0:t.sfdcCredential}function qi({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:i=!0}){return(0,te.default)(()=>Re(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:i}),{retries:re,factor:1})}function _p(s,e,t){return(0,te.default)(()=>Ce({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:re,factor:1})}function kr(s,e,t,r,i,n,o=re){return(0,te.default)(()=>pn("/result/run/test",{runId:e,testId:t,resultId:r,status:i,projectId:s,runnerVersion:vI,...n}),{retries:o,factor:1})}function au(s,e,t,r,i,n,o,a){return(0,te.default)(()=>pn("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:i,startTime:n,endTime:o,projectId:a}),{retries:re,factor:1})}async function cu({executionId:s,projectId:e,labels:t,startTime:r,executions:i,config:n,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(uo(),_f));return Ce({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:i,status:"RUNNING",config:n,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:c,isLocalRun:l}},retry:3})}function Ao(s,e,t,r,i={},n=void 0,o=void 0){let a=Date.now();return(0,te.default)(()=>pn("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:i,remoteRunId:n,resultExtraData:o}),{retries:re,factor:1})}async function un(s,e,t,r,i){return(0,te.default)(()=>Ce({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:i},timeout:12e4}),{retries:re,factor:1})}function $u({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:i,suiteNames:n,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:i,suiteNames:n,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}}),{retries:re,factor:1})}async function on({appId:s,projectId:e}){try{return await(0,te.default)(()=>Re(`/mobile-app/app/${s}?projectId=${e}`),{retries:re,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function Up(s){try{return await(0,te.default)(()=>Re(`/plan/project/${s}/usage-current-billing-period`),{retries:re,factor:1})}catch(e){Ft.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Mu(s,e,t){return(0,te.default)(()=>Re(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:re,factor:1})}function Mr(s,e,t,r){return(0,te.default)(()=>Re(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:re,factor:1})}function Il(s,e){return Ce({url:`/grid/keep-alive?reqId=${se()}`,body:{projectId:s,slots:e},timeout:1e4})}function Rl(s,e,t,r,i){return Ce({url:`/grid/release?reqId=${se()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:i}})}function xl(s){return Ce({url:"/grid/hybrid/provider",body:s})}function Cl(s){return(0,te.default)(()=>Re("/grid/grid-slot",{...s,reqId:se()}),{retries:re,factor:1})}async function Bp({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:i,publicIp:n,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d}){var m,u;try{return await(0,te.default)(()=>Ge({url:`${he()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:i,publicIp:n,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d},timeout:6e4}),{retries:re,factor:1})}catch(f){if(Ft.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(Lp.default[y](Lp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Ft.error("Error parsing error message from server",f)}throw f}}async function CI(){if(st)return{editorUrl:st};try{return await(0,te.default)(()=>Re("/system-info/editor-url"),{retries:re,onFailedAttempt:s=>{if(s.attemptNumber>=re)throw s},factor:1})}catch(s){return Ft.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Al(s){return(0,te.default)(()=>Re("/grid",{companyId:s}),{retries:re,factor:1})}function ru(s,e,t){return(0,te.default)(()=>Re(`/real-data/${e}?${t}&projectId=${s}`),{retries:re,factor:1})}function ta(s,e,t,r,i){return(0,te.default)(()=>Ce({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:i}}),{retries:re,factor:1})}function Fu(s,e,t,r){return(0,te.default)(()=>Ce({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:re,factor:1})}function xu(s,e,t,r){return(0,te.default)(()=>Ce({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:re,factor:1})}function AI(s){return s.startsWith("/")?s:`/${s}`}function PI(s,e,t){let r=AI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Gb(s,e,t,r,i,n="application/octet-stream"){let o=null;n==="application/json"&&(o=".json");let a=`${i}_${se()}${o||""}`,c=`${e}/${t}/${a}`,l=PI(c,EI,s),d=Buffer.from(Wb.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,te.default)(()=>II(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:re,factor:1}),l}function lu({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:i,previousTestResultId:n,testResult:o}){return(0,te.default)(()=>Ce({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:i,previousTestResultId:n,testId:t,runId:e,testResult:o}}),{retries:re,factor:1})}async function Dp(s){try{return await Re(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Ft.warn("could'nt get applitools integration data.",{err:e}),{}}}async function jp(s,e){try{return await pn("/tunnel",{companyId:s,routes:e})}catch(t){return Ft.warn("could'nt get tunnel.",{err:t}),{}}}async function $p(s,e){try{return await Ce({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Ft.warn("could'nt get tunnel.",{err:t});return}}async function Wp(s,e){try{return await Vb(`/tunnel/${e}`,{companyId:s})}catch(t){Ft.warn("could'nt get tunnel.",{err:t});return}}function Vp(s){return Ge({url:`${he()}/result/remoteRunFailure`,body:s})}async function an({projectId:s,projectType:e,gridId:t,companyId:r,selectors:i}){let n=`${SI}/mobileDevices/${t}/${r}?projectType=${e}`;n=i?`${n}&selectors=${encodeURIComponent(i)}`:n;try{return await(0,te.default)(()=>Re(n,{projectId:s}),{retries:re,factor:1})}catch(o){return Ft.warn("could'nt get devices from grid.",{err:o}),null}}async function up({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:re,factor:1})}async function pp(s){return(0,te.default)(()=>Ce({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:re,factor:1})}async function Yl(s,e){return(0,te.default)(()=>Ce({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:re,factor:1})}async function Xl(s,e,t){return(0,te.default)(()=>Ce({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:re,factor:1})}async function Ql(s,e,t){return(0,te.default)(()=>pn("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:re,factor:1})}function Zl(s,e,t){return Ce({url:`/slot-management/keep-alive?reqId=${se()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function kI(s,e){return await we(`${Gs}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function Sl(s){try{return await Re("/v2/project/validateUserAccessKey",s),!0}catch(e){return Ft.error("error validating user access key",{error:e}),!1}}async function Gp(s,e){let[t]=await Re("/capabilities?",{projectId:s,name:e});return t}var Lp,dr,Wb,te,Np,vI,Ft,re,SI,EI,du,Iu,Uu,Po,ge=I(()=>{"use strict";Lp=R(require("chalk")),dr=R(require("lodash")),Wb=R(require("pako"));F();oe();ae();He();ut();te=R(require("p-retry")),Np=R(require("object-hash"));X();W();Pp();vI=it(),Ft=P("testim service api"),re=3,SI="/grid",EI="test-result-artifacts";du=async(s,e)=>(0,te.default)(()=>Re("/grid/lt/config",{companyId:s,...e&&{projectId:e}}),{retries:re,factor:1}),Iu=async s=>(0,te.default)(()=>Re(`/labFeature/v2/project/${s}`),{retries:re,factor:1});Uu=dr.memoize(async(s,e,t,r)=>{if(!dr.isEmpty(r))return await Gb(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Np.default)(r)}:${e}:${t}`),Po=dr.memoize(async(s,e,t,r,i)=>!r||dr.isEmpty(r)?void 0:await Gb(s,e,t,JSON.stringify((()=>{let o=dr.clone(r);if(i!=null&&i.hiddenParams){let a=i.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:Vc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Np.default)(r)}:${e}:${t}`)});function Za(){return it()}var Hp=I(()=>{"use strict";F()});function DI(s){K.EXTENSION!==s&&process.nextTick(()=>{try{(ve(),ze(or)).getSessionPlayer()}catch{}})}function LI(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let i=r.color||"yellow",n=r.bgColor||"bgBlack";console.log(qp.default[n](qp.default[i](r.text)))})}function NI(s,e){let{serviceUrl:t}=s;Hs(t),Ot(async()=>s,Qr.CACHE_FN_NAME,Qr.TTL,{serviceUrl:t})(),Ut.setRegion(xg[Ts(e)])}async function dn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:i,useLocalChromeDriver:n,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,d=Boolean(i==null?void 0:i.general),m=Boolean(n||o),u=d?_I:OI,f=Za(),h=jc(),g=await Ym(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Nb()}catch(T){Hb.error("failed to get public ip",T)}let v=!0;M("before initializeUserWithAuth");let b=await Ot(async()=>(DI(a),v=!1,await Bp({projectId:e,token:t,branchName:s.branch,lightweightMode:i,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 LI(b),NI(b.clientConfig,e),s.publicIps=[b.clientPublicIp],M("after initializeUserWithAuth"),y&&b.clientPublicIp&&b.clientPublicIp!==y&&(Hb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:b.clientPublicIp}),s.publicIps.push(y)),yf(b.authData,{projectId:e,token:t,userAccessKey:r,publicIp:b.clientPublicIp,initializedFromCache:v}),b}var qp,Hb,OI,_I,qb=I(()=>{"use strict";qp=R(require("chalk"));We();ge();er();ut();qa();ae();W();de();Hp();F();as();oe();Oo();Hb=P("initializeUserWithAuth"),OI=1e3*60*5,_I=1e3*60*60*10});async function Jb(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await ro():s.chromeBinaryLocation,e=ui({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!==K.EXTENSION&&await Rr(s.playerLocation,s.canary),s.mode!==K.SELENIUM&&s.mode!==K.APPIUM&&!s.ext&&await dl(s.extensionLocation);let t;if(s.installCustomExtension){let i=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await pl(s.installCustomExtension,i)}return await e,t}async function Yb(s){var o;MI.info("prepare MockNetwork",{location:s});let e=await Uc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>zb*1e6)throw new Error(`${zp} exceeded ${zb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${zp} cannot be parsed.${ec.EOL}${a}`)}let i=new Kb.default;if(!i.validate(Zc,r)){let a=(o=i.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(ec.EOL);throw new Error(`${zp} is malformed.${ec.EOL}${a}`)}return r.entries}var ec,Kb,zb,zp,MI,Kp=I(()=>{"use strict";ec=R(require("node:os"));F();Pm();di();Kb=R(require("ajv"));ae();hl();W();qb();zb=1,zp="JSON file supplied to --mock-network-pattern",MI=P("prepare runner")});function tT(s){return s.start&&us(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function rT(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new x("Agent port is not number");let t=ko(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 sT=I(()=>{"use strict";Fi();ps();X()});var Ms,Qp,iT=I(()=>{"use strict";Ms="SECRETS",Qp={get secretsKey(){return Ms},get proxySecrets(){return new Proxy({},{get(s,e){return`${Ms}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[Ms]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(Ms):JSON.stringify(s).includes(Ms)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${Ms}\\.\\w+`,"g"));return r==null||r.map(i=>{let n=i.split(".")[1];n&&e.add(n)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^${r}\\.(\\w+)$`),n=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(i);if(l){let d=l[1];o[c]=e[d]??a}}else typeof a=="object"&&a!==null&&n(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(i);if(l){let d=l[1];o[a]=e[d]??c}}else typeof c=="object"&&c!==null&&n(c)})};n(s)}}});var sd={};z(sd,{doLogin:()=>rd,getProjectId:()=>WI,getToken:()=>VI});async function WI(){return aT("projectId")}async function VI(){return aT("token")}function oT(s,e){return Promise.race([s,pe(e).then(()=>{throw new ce("timeout")})])}async function GI(){let s=(await import("express")).default(),e=async function(){return oT(new Promise(i=>{s.get("/loginInfo",(n,o)=>{i(JSON.parse(Buffer.from(n.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,i)=>{let n=s.listen(42543,o=>{o&&i(o),r(n.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),ke)),{editorUrl:i}=await r();So(`${i}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${st||br}`)}return await e}async function rd({overwriteExisting:s=!0,projects:e=null}={}){let t=Zp.homedir(),r=ed.join(t,".testim");if(await ye(r)&&!s)return;let n={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await oT(GI(),62e3).catch(()=>null)),e!=null&&e.token){n.token=e.token,n.projectId=e.projectId,c.succeed(),await nT(r,n);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}))});n.token=l.project.ci.token,n.projectId=l.project.id,await nT(r,n);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function nT(s,e){await td.promises.writeFile(s,rc.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function aT(s){let e=Zp.homedir(),t=ed.join(e,".testim"),r=await ye(t),i={};if(r)try{i=rc.parse((await td.promises.readFile(t)).toString())}catch{}return i||={},i[s]}var Zp,ed,rc,td,sc=I(()=>{"use strict";Zp=R(require("os")),ed=R(require("path")),rc=R(require("yaml"));F();td=require("fs");X();ql();oe()});var hT={};z(hT,{process:()=>ZI,program:()=>p});var nd,dT,ic,mT,xt,_e,fT,HI,Ue,qI,ad,zI,KI,lT,gT,mn,od,nc,cd,id,Rt,uT,JI,YI,p,XI,QI,pT,ZI,yT=I(()=>{"use strict";nd=R(require("ms")),dT=R(require("chalk")),ic=R(require("node:fs")),mT=R(require("node:url")),xt=R(require("lodash")),_e=R(require("node:path"));F();Fi();sT();er();fT=require("commander");ae();X();qr();F();de();iT();Jo();Oo();oe();mu();HI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ue=(s,e)=>(e.push(s),e),qI=s=>(e,t)=>{if(t!==void 0)throw new x(`The ${s} flag can only be specified once.`);return e},ad=new fT.Command,zI=s=>s.split(","),KI=(s,e)=>!s||s.length===0?e:s,lT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],gT=()=>{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 i(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function n(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")}ad.help(g=>g.split(`
403
+ const downloadAndUploadFile = ${VE()};
404
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Fy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var Ra,xa,jy=I(()=>{"use strict";Ra=require("url");me();xa=class extends q{async updateBaseUrl(e){let t=new Ra.URL(e),r=new Ra.URL(this.context.recordedBaseUrl),i=new Ra.URL(this.context.baseUrl);return t.host===r.host&&r.host!==i.host&&(t.host=i.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 Aa,$y=I(()=>{"use strict";me();F();Aa=class extends q{async performAction(){await pe(this.step.durationMS||0)}}});var Ca,Wy=I(()=>{"use strict";me();Ca=class extends q{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var tn,Vy=I(()=>{"use strict";me();tn=class extends q{async runApiInAut(e){var i;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let n=await this.driver.executeCodeAsync(r,t,e);return(n==null?void 0:n.value)||{}}catch(n){throw(i=n==null?void 0:n.message)!=null&&i.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.'):n}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,i={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},n=t.sendViaWebApp?await this.runApiInAut(i):await this.runApiInBg(i),o=n.result||{},a={method:t.method,status:o.status,url:t.url};return n.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 Pa,Gy=I(()=>{"use strict";me();Pa=class extends q{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 Hy,Ju,Xu,qy=I(()=>{"use strict";Hy=R(require("@applitools/spec-driver-webdriverio"));Sn();ve();Ju=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=Rd["@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:Hy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,i){let{EyeSdkBuilder:n}=ee(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return n.rememberCreatedBatch(r,i),o}},Xu=new Ju});var zy,Yu,rn,Ky=I(()=>{"use strict";zy=R(require("lodash"));me();W();qy();Yu=P("pixel-validation-step-action"),rn=class extends q{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:i,testResultId:n}=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)||n,c=await Xu.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:i}),g={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};zy.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),Yu.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()},Yu.info("Applitools SDK step executed successfully (selenium mode)",{projectId:this.context.projectId})}catch(f){Yu.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Xu.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ps,Qu=I(()=>{"use strict";Es();Y();ga();Ps=class extends lr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:n="",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 Ss(n,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 ce?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ur,Jy=I(()=>{"use strict";Qu();ur=class extends Ps{isFailedResult(e){return e===!1}}});var ka,Xy=I(()=>{"use strict";Qu();ka=class extends Ps{isFailedResult(e){return!e}}});var Oa,Yy=I(()=>{"use strict";Es();me();Y();Oa=class extends q{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:i,stepResultId:n,timeToPlayBeforeExec:o}=this.context;try{return{data:await vs(e,r,i,t,n,o),success:!0}}catch(a){return a instanceof Pt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ce?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Br,Qy=I(()=>{"use strict";me();Br=class extends q{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,Zy=I(()=>{"use strict";me();be=class extends q{async performAction(){var r,i;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((n,o)=>this.context.playback.sfdcAddLog(n,o)));t.log.info(`BEGIN STEP '${(i=(r=this.step).getStepPreview)==null?void 0:i.call(r)}'`);try{let n=this.context.sfdcTestActions;if(n===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,n,this.context)}}catch(n){return{success:!1,reason:n.reason||n.message,exception:n,shouldRetry:!1}}finally{t.releaseObjects()}}}});var _a,eb=I(()=>{"use strict";me();_a=class extends q{async performAction(){var r,i;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((n,o)=>this.context.playback.sfdcAddLog(n,o)));t.log.info(`BEGIN STEP '${(i=(r=this.step).getStepPreview)==null?void 0:i.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(n){return{success:!1,reason:n.reason||n.message,exception:n,shouldRetry:!1}}finally{t.releaseObjects()}}}});var La,tb=I(()=>{"use strict";me();La=class extends q{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 GE(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Da(s,e){GE(HE,e),e.registerLocateStepActionUtils(Yi.getUtils(s))}var HE,Zu=I(()=>{"use strict";Qh();ty();uy();py();my();hy();Ty();wy();vy();Sy();Ry();xy();Ay();ky();Ly();By();jy();$y();Wy();Vy();Gy();Ky();Jy();Xy();Yy();Qy();Zy();eb();tb();HE={locate:Yi,scroll:ua,mouse:pa,submit:Ta,text:ma,"special-key":ha,"user-code":zt,"validation-code-step":zt,"wait-for-code-step":zt,"action-code-step":zt,"condition-step":Cs,"skip-code-step":Cs,"element-code-step":Cs,"evaluate-expression":da,"text-validation":Zi,"wait-for-text-validation":Zi,"select-option":ba,"drop-file":Sa,"input-file":Ia,hover:wa,navigation:xa,wheel:va,sleep:Aa,refresh:Ca,"keyboard-shortcut-step":ya,"api-validation":tn,"api-action":tn,"api-code-step":zt,"extract-text":Pa,"simple-ui-verification":rn,"wait-for-simple-ui-verification":rn,"cli-validation-download-file":Br,"cli-wait-for-download-file":Br,"network-validation-step":Br,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":ka,"node-package":Oa,"email-code-step":zt,"cli-email-code-step":ur,"sfdc-internal-test-step":La,"sfdc-recorded-step":_a,"sfdc-step-login":be,"sfdc-step-loginas":be,"sfdc-step-logout":be,"sfdc-step-sobjectcreate":be,"sfdc-step-sobjectdelete":be,"sfdc-step-findrecord":be,"sfdc-step-quickaction":be,"sfdc-step-sobjectedit":be,"sfdc-step-sobjectvalidate":be,"sfdc-step-launchapp":be,"sfdc-step-wait-for-page-load":be,"sfdc-step-closeconsoletabs":be,"sfdc-step-relatedlistaction":be,"sfdc-step-permission-validation":be,"sfdc-step-convert-lead-to-opportunity":be,"sfdc-step-quotelineeditor":be,"sfdc-document-validation":Br,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var rb,qE,ks,ep=I(()=>{"use strict";rb=["simple-ui-verification","wait-for-simple-ui-verification"],qE=[...rb,"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"],ks=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=n=>{let o=this.getTotalStepTimeLeftToPlay(e,n),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),i=qE.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,i),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return rb.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,i=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),i)}}});var ib={};z(ib,{SeleniumTestPlayer:()=>sn});var sb,zE,sn,tp=I(()=>{"use strict";F();sb=require("@applitools/eyes-sdk-core");$i();Y();W();Vu();zh();zu();ca();Xh();Ku();ve();Zu();ep();ae();zE=P("SeleniumTestPlayer"),sn=class{constructor(e,t,r,i,n=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new ks(la());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=i??new _r;let d=new aa(this.driver);this.stepActionFactory=new l(d),Da(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new na(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Jh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new As(this.driver),FrameLocator:m,portSelector:oa,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:sb.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=n,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,i){i!=null&&i.isTabOpener&&this.tabService.addNewPopup(this.id,i.id).catch(()=>null)}async onDone(){var r,i;let{commonConstants:e}=ee(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(n){n instanceof ce&&await((i=this.driver)==null?void 0:i.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)){zE.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let i=r.at(-1);await this.tabService.addNewTab(this.id,i,e,t),await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let i=await this.driver.getTabIds(),n=[new URL(st||yr).hostname].concat(r);for(let o of i.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(n.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 sp={};z(sp,{WorkerSelenium:()=>rp});function JE(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Na,KE,rp,ip=I(()=>{"use strict";F();We();Ji();W();Dt();$o();oe();$u();Y();tp();ve();ut();Na=P("worker-selenium"),KE=1e9,rp=class extends Mt{initPlayer(t){return new sn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,i,n){M("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=i;this.windowUtils=new xs(this.id,o),i.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:n,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:l,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.SELENIUM,customCapabilities:t.customCapabilities}),M("in WorkerSelenium after driver.init"),await i.addTab(void 0,{skipLoadInfo:l}),M("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,KE),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 Ct||d||m?new Ct(`Page '${c}' is not available`):(Na.error("failed to navigate to page",{baseUrl:c,err:l,whitelistedPublicIp:io(),initializedFromCache:no()}),l)}}async runTestOnce(t,r){var m;let{manifestVersion:i,localAssetService:n}=ee(),{driver:o,sessionPlayer:a}=r,c=i||"runner";Z.onWaitToTestComplete(this.id),JE(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===K.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),n.initialize({serverUrl:this.options.localRCASaver});let l=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(l=(await Gi(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 ce&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await n.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Na.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&&(Na.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 Na.error("failed to run test once",{err:u}),u}}}});var nb,ob,qe,XE,np,Et,Ma=I(()=>{"use strict";nb=R(require("ora")),ob=require("jimp");ae();He();ge();W();oe();ve();de();qe=P("mobile-grid-service"),XE="https://tdc.tricentis-cloud.com",np=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||wc}/${jd}/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),i=this.getHeaders(e),n=this.buildRequestBody(e,t);try{await Ge({url:r,headers:i,body:n})}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 i=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let n=await we(i,void 0,this.getHeaders(e));return this.extractTDCDeviceConnection(n,e.accessToken)}catch(n){throw qe.error("error while getting automation config for device",{error:n,deviceId:t}),n}}extractTDCDeviceConnection(e,t){let r=Object.keys(e)[0],i=e[r].driver_url,n=new URL(i);return{hostname:n.hostname,port:Number(n.port),protocol:n.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 i=(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:i}}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:i,companyId:n,gridId:o}){var a,c,l;if(t===N.TESTIM_TDC){let d=await on({projectId:r,projectType:i,companyId:n,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,i,n=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=i,h=t.capabilities,g=h.platformName,y;if(f===N.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:b}=ee();y=b(t.capabilities,n)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,d,m,u,n);let v=await this.buildRemoteResultLink(i.gridData,t.sessionId,h);return await Pr(l,o,a,c,"RUNNING",{device:y,...v&&{remoteResultLink:v}}),qe.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:y,remoteResultLink:v,gridType:f}),y}getOsVersion(e,t){var i;let r=e.platformVersion;return!r&&t===N.BROWSERSTACK?(i=e.mobile)==null?void 0:i.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,i,n){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,n),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(c,"base64"),m=await ob.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/l.width,width:u,height:f}}catch(o){return qe.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:i==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,i,n,o,a,c,l,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,i,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:n,projectId:o,projectType:a,companyId:c,gridId:l})]),f=this.getOsVersion(e,n);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:i,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===N.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Gs}/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?`${XE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let i=(await we(`${e}/api/devices`)).find(n=>n.udid===t);if(!i)throw new Error(`device ${t} not found`);return{udid:i.udid,name:i.name,model:i.model,height:i.height,width:i.width,geo:"local",osVersion:i.osVersion,osType:i.deviceType.toLowerCase(),scaleFactor:i.scaleFactor??0,isVirtual:i.virtual??!1,minApiVersion:i.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:i,testId:n,testResultId:o}=r,{project:a,localTmaUrl:c}=t,l=await this.getTmaDeviceDetails(c,e);return await Pr(a,i,n,o,"RUNNING",{device:l}),qe.info("device details updated on testResult",{testResultId:o,executionId:i,testId:n,device:l}),l}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let i=e.type,n=t.mobileApp,o=this.gridsAppIdGetter[i]({testRunHandler:t,mobileApp:n,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 ap({gridAppId:o,gridId:e.gridId,projectId:r,gridType:i,appId:n.appId,gridHost:e.host})),o):t.getAppPathByGridType(i,e.gridId,n)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let i=await nn({appId:e,projectId:t});return{appUrl:`${he()}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Bd*60))+1)*60*1e3,Math.max(Ud,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:i,gridType:n}){let a={[N.BROWSERSTACK]:{name:"Browserstack"},[N.TESTIM_TVC]:{name:"Mobile Virtual Grid"}}[n].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,nb.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 op({projectId:e,gridId:i,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:i,gridType:n,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:i,gridType:n});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let i="",n,{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 i;if(c){qe.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let v=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:d});i=v.appUrl,n=v.mobileApp,e.nativeApp=n}else qe.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:o}),i=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 v=t.projectData.type,b=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:v});b&&(qe.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),i=g),!b&&y&&(qe.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),i=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!b&&!y&&qe.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&y&&(i=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),i}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){let{accessToken:i,user:n,host:o,key:a,type:c,apiUrl:l}=t;if(c===N.BROWSERSTACK){let d=`${Gs}/recent_apps`,m=await this.fetchWithUserAndPasswordAuth({url:d,user:n,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:n,key:a})).items.some(u=>u.id===e)}if(c===N.TESTIM_TDC){let d=`${l}/${vc}/apps`;return l||(d=`${wc}/${vc}/apps`),(await this.fetchWithTokenAuth({url:d,accessToken:i,authType:"Bearer"})).apps.some(u=>u.app_id===e)}if(c===N.TESTIM_TVC){let d=`${$d}/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 i={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await we(e,void 0,i)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:i}){let n={Authorization:`${r} ${t}`,...i&&{"User-Agent":i}};return await we(e,void 0,n)}},Et=new np});function ab({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"&&!YE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function QE({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 ZE(s){let{testName:e,executionId:t,testResultId:r,customTag:i}=s,n=[{executionId:t},{testResultId:r}];return e&&n.push({testName:e}),i&&n.push({customTag:i}),n}function eI(s,e,t,r){let{fullReset:i,setNoReset:n,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"]:ZE(t),["tdc:enableBatch"]:c,...!i&&{"appium:noReset":n},...l&&{["tdc:newCommandTimeout"]:600,"appium:newCommandTimeout":600},...r}}function Fa(s){return"id"in s?s.id:s.packageName}function tI(s){return{"tdc:app.id":s}}function rI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:i,androidActivityWait:n}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":i},l=i==null?void 0:i.startsWith("http");i&&!l&&(c=tI(i));let m=()=>o===void 0&&i?!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":Fa(r)},...i&&c};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...n&&{"appium:appWaitActivity":`${n}, *`},...r&&{"appium:appPackage":Fa(r),"appium:appActivity":r.activity??".*"},...i&&c};default:throw Error(`unsupported mobile project ${s}`)}}function Ls({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,appiumPrefix:n="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${n}autoAcceptAlerts`]:!0,[`${n}automationName`]:o?"WaldoTestim":"XCUITest",[`${n}fullReset`]:!0,...t&&{[`${n}bundleId`]:Fa(t)},...r&&{[`${n}app`]:r},...e};case"android":return{platformName:"Android",[`${n}autoGrantPermissions`]:!0,[`${n}automationName`]:o?"WaldoTestim":"UiAutomator2",...i&&{[`${n}appWaitActivity`]:`${i}, *`},...t&&{[`${n}appPackage`]:Fa(t),[`${n}appActivity`]:t.activity??".*"},...r&&{[`${n}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function cb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:i,options:n,gridInfo:o,shouldRunInEnhancedMode:a,customCapabilities:c}){let l=eI(o.type,n,i,c);return rI({projectType:s,sessionCaps:l,options:n,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function lp({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 up({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:i,dynamicAllocation:n}=e;return s||(i!=null&&i.deviceName?i.deviceName:n!=null&&n.deviceNameRegex?n.deviceNameRegex:t==="ios"&&r===N.BROWSERSTACK?"iPhone.*":".*")}function sI(s,e){let{androidToken:t,iosToken:r}=s,i=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(i&&!r)throw Error("missing ios token for testim virtual cloud");if(!i&&!t)throw Error("missing android token for testim virtual cloud");return i?r:t}function lb(s,e,t){return s?Object.entries(s).reduce((r,[i,n])=>{if(e(i)){if(!t)return r[i]=n,r;let o=i.replace(t,"");r[o]=n}return r},{}):{}}function iI(s){return lb(s,e=>e.startsWith("browserstack."),"browserstack.")}function nI(s){return lb(s,e=>!e.startsWith("browserstack."))}function ub(s){return!s||!pb(s)?"2.0.0":s}function pb(s){return s.split(".")[0]==="2"||s.includes("appium2")||["latest","stable"].includes(s)}function db({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let i=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,n=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&n.test(s),c=e==="android"&&(i.test(s)||a),l=e==="ios"&&o.test(s),d=c||l;if(t){let m=pb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Os(s,e){let t={};return Object.entries(s).forEach(([r,i])=>{let n=r.startsWith(e)?r:`${e}${r}`;t[n]=i}),t}async function oI(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,options:n,gridInfo:o,sessionTags:a,testRunConfig:c,shouldRunInEnhancedMode:l,customCapabilities:d}=s,{osVersion:m,deviceName:u}=n,f=(c==null?void 0:c.mobile)||{},{type:h}=o,g=sI(o,e),y=await on({gridId:o.gridId,projectType:e,projectId:n.project,companyId:n.company.companyId}),v=y==null?void 0:y.find(({udid:A})=>{var _;return((_=f.staticAllocation)==null?void 0:_.deviceUdid)===A}),b=(v==null?void 0:v.osVersion)??lp({osVersion:m,mobileConfig:f}),T=(v==null?void 0:v.name)??up({deviceName:u,mobileConfig:f,projectType:e,gridType:h}),w=Ke(n.editorUrl,n.project,a.testId,a.testResultId,a.branch),E={device:T,os_version:b,"waldo:displayName":`${a.testName}-${a.executionId}-${a.testResultId}`,"waldo:externalUrl":w,...l&&{"waldo:automationName":"WaldoTestim"},...d};return E["waldo:options"]||(E["waldo:options"]={}),E["waldo:options"].token||(E["waldo:options"].token=g),Ls({projectType:e,sessionCaps:E,nativeAppMetadata:t,appPath:r,androidActivityWait:i,shouldRunInEnhancedMode:l})}function aI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:i,gridInfo:n,sessionTags:o,testRunConfig:a,customCapabilities:c}){let{osVersion:l,deviceName:d}=i,m=(a==null?void 0:a.mobile)||{},{type:u}=n,f=lp({osVersion:l,mobileConfig:m}),h=up({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),g=(0,It.omit)({...i.saucelabs},["automationName","platformName"]),y={...g["sauce:options"]};delete g["sauce:options"];let v={...c==null?void 0:c["sauce:options"]},b=(0,It.omit)(c,"sauce:options"),T=y.appiumVersion||v.appiumVersion,w=g.platformVersion||b.platformVersion||f;if(db({osVersion:w,projectType:s,appiumVersion:T})){let A={debug:!0,networkLogs:!0},_={user:n.user,key:n.key,name:o.testResultId,build:o.executionId,appiumVersion:ub(T??"stable"),deviceName:h,tags:Object.values(o)},B={"appium:platformVersion":f,"appium:deviceName":h,...Os(g,_s),...Os(b,_s),"sauce:options":{...A,..._,...(0,It.omit)(y,"appiumVersion"),...(0,It.omit)(v,"appiumVersion")}};return Ls({projectType:s,sessionCaps:B,appiumPrefix:_s,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let E={"saucelabs.user":n.user,"saucelabs.key":n.key,platformVersion:f,deviceName:h,tags:Object.values(o),name:o.testResultId,build:o.executionId,...g,...y,...b,...v};return Ls({projectType:s,sessionCaps:E,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function cI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,options:n,gridInfo:o,sessionTags:a,testRunConfig:c,customCapabilities:l}){let{osVersion:d,deviceName:m}=n,u=(c==null?void 0:c.mobile)||{},{type:f}=o,h=lp({osVersion:d,mobileConfig:u}),g=up({deviceName:m,mobileConfig:u,projectType:e,gridType:f}),y=iI(n.browserstack),v=(0,It.omit)(nI(n.browserstack),["automationName","platformName","project","build","name"]),b={...l==null?void 0:l["bstack:options"]},T=(0,It.omit)(l,"bstack:options"),w=y.appiumVersion||b.appiumVersion,E=v.platformVersion||T.platformVersion||h,A=O.flags.enableAppium2BrowserStack.isEnabled(),_={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`};if(A||db({osVersion:E,projectType:e,isBrowserStack:!0,appiumVersion:w})){let V={..._,userName:o.user,accessKey:o.key,appiumVersion:A?"2.0.1":ub(w),debug:!0,networkLogs:!0},S={"appium:platformVersion":h,"appium:deviceName":g,...Os(v,_s),...Os(T,_s),"bstack:options":{...V,...(0,It.omit)(y,"appiumVersion"),...(0,It.omit)(b,"appiumVersion")}};return Ls({projectType:e,sessionCaps:S,appiumPrefix:_s,nativeAppMetadata:t,appPath:r,androidActivityWait:i})}let B={..._,os_version:v.platformVersion||h,device:v.deviceName||g,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...v,...Os(y,"browserstack."),...T,...Os(b,"browserstack.")};return Ls({projectType:e,sessionCaps:B,nativeAppMetadata:t,appPath:r,androidActivityWait:i})}async function lI(s){if(N.TESTIM_TDC===s.gridInfo.type)return cb(s);if(N.TESTIM_TVC===s.gridInfo.type)return await oI(s);if(N.SAUCELABS===s.gridInfo.type)return aI(s);if(N.BROWSERSTACK===s.gridInfo.type)return cI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function uI(s,e){var l,d;let{staticAllocation:t,dynamicAllocation:r,type:i}=e||{},{deviceName:n,osVersion:o,deviceUdid:a}=s,c={};return i==="dynamic"&&(!n&&((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)),i==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),n&&(c.manufacturer=n),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function mb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:i,testRunConfig:n}=s,{selectedGrid:o}=(n==null?void 0:n.mobile)||{};if(n!=null&&n.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);ab({nativeAppMetadata:t,appPath:i,gridInfo:e});let a=Et.getGridConnection(e),c=await lI(s);if(e.type===N.TESTIM_TDC){let y=uI(r,n==null?void 0:n.mobile);if(!(0,It.isEmpty)(y)){let v=Object.entries(y).map(([b,T])=>T.split(",").map(w=>w===".*"||w==="="?"":`${b}:${w}`).join(",")).join(" ").trim();c["tdc:selector"]=v}}let l=e.type===N.TESTIM_TVC?{alwaysMatch:c}:c,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,cp.default)("2m"),f=(0,cp.default)("12m"),h=wr(O.flags.appiumConnectionRetryCount.getValue(),m),g=wr(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 fb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:i,appPath:n,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=i;ab({nativeAppMetadata:r,appPath:n,gridInfo:t}),QE({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 Et.getGridDirectConnection(t,d),f=cb({projectType:e,nativeAppMetadata:r,appPath:n,androidActivityWait:o,options:i,sessionTags:a,testRunConfig:c,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:i.appiumLogLevel}}function gb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,customCapabilities:n}=s,o={...n,dontStopAppOnReset:!0,fullReset:!1},a=Ls({projectType:e,sessionCaps:o,nativeAppMetadata:t,appPath:r,androidActivityWait:i});return e==="ios"&&delete a.app,a}function hb(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 cp,It,_s,YE,pp=I(()=>{"use strict";cp=R(require("ms"));de();oe();Ma();It=require("lodash");F();ge();_s="appium:",YE=[N.BROWSERSTACK,N.SAUCELABS,N.TESTIM_TDC,N.TESTIM_TVC]});var Ua,bb=I(()=>{"use strict";Ua=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 Ba,Tb=I(()=>{"use strict";F();Ba=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=ii;this.getLinksFromUnescapeHTML=ni}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 dp,ja,wb=I(()=>{"use strict";W();dp=P("mobile-frame-locator-mock"),ja=class{foundFrameCallback(){return dp.info("foundFrameCallback-mock invoked"),{}}locate(){return dp.info("locate-mock invoked"),{}}async findFrame(){return dp.info("findFrame-mock invoked"),{}}}});var pI,Sb,vb,Ds,mp=I(()=>{"use strict";pI=R(require("webdriverio")),Sb=require("@applitools/eyes-sdk-core");bb();zu();W();Tb();Ku();ve();Zu();wb();ep();vb=P("appium-test-player"),Ds=class{constructor(e,t,r,i=pI,n=void 0,o=void 0){this.id=e;this.driver=i;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=ee(),m=new Ba(this.driver);this.stepActionFactory=new l(m),Da(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new ks(la()),this.sessionPlayer=new a(e,{tabService:new Ua,cookieUtils:void 0,FrameLocator:ja,portSelector:oa,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Sb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=n,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,i){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:i}=e,n={executionId:t,testResultId:r,sessionId:i==null?void 0:i.sessionId};try{i!=null&&i.sessionId&&(await(i==null?void 0:i.endSession()),vb.info("appium session deleted",{...n}))}catch(o){vb.error("error while deleting appium session",{...n,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 dI(s){return await we(`${s}/api/status`)}async function Eb(s,e){return await we(`${s}/api/devices/${e}/status`)}async function Ib(s){if((await dI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Rb=I(()=>{"use strict";He()});var xb={};z(xb,{WorkerLocalTma:()=>yp});var jr,fp,gp,hp,yp,Ab=I(()=>{"use strict";He();pp();Ji();F();W();Dt();mp();ve();Rb();Ma();jr=P("worker-appium"),fp=class extends Error{},gp=class extends Error{},hp=class extends Error{},yp=class extends Mt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Ds(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:i}=await import("linkedom"),n=new r(this.sessionData.serverAddress,this.sessionData.sessionId,i,!1);return t.sessionPlayer.playbackManager.appiumApi=n,n}async getBrowserOnce(t,r,i,n){var E;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 Ib(o);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=i,u=c.type,f=this.options.appId;if(f){let{mobileApp:A}=await Et.getMobileAppDataByAppId({appId:f,projectId:l,token:d});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,v=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!v)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:b,version:T},w]=await Promise.all([this.getAppStateFromDevice(o,a,v),Eb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(jr.info("device status and app state",{deviceStatus:w,appInstalled:b,version:T,executionId:this.executionId,testResultId:this.testResultId}),!b&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!b&&y&&(await this.installApp(o,a,y),jr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let A={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},_=gb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:n,options:this.options,testRunConfig:this.testRunConfig,customCapabilities:t.customCapabilities}),B={capabilities:{udid:a,..._}};jr.info("requesting new appium session from TMA",{tmaSessionSettings:B,executionId:this.executionId,testResultId:this.testResultId});let V=await this.requestNewAppiumSessionFromTma(o,B,g);this.sessionData=V;let S=await m.attach({sessionId:V.sessionId,capabilities:_,options:{capabilities:_}});this.device=await Et.updateTmaDeviceDetails(a,this.options,t),jr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:S.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:S.capabilities})}catch(A){throw jr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,i){var n,o;try{let a=await Ge({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:i.name,version:i.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(n=a.response)==null?void 0:n.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new hp(c):a}}async getAppStateFromDevice(t,r,i){let n=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${n}`,c=(await we(o)).find(l=>"id"in l?l.id===i:l.packageName===i);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,i){var n,o;try{let a=await $t(i);await Ys(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(n=a.response)==null?void 0:n.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new gp(l,{cause:a})}}handleDeviceNotFoundError(t){var i,n;let r=(n=(i=t.response)==null?void 0:i.body)==null?void 0:n.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new fp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:i,localAssetService:n}=ee(),{sessionPlayer:o}=r,a=i||"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),n.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 n.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw jr.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw jr.error("failed to run test once",{err:l}),l}}}});var Pb={};z(Pb,{WorkerAppium:()=>bp});var Cb,$r,bp,kb=I(()=>{"use strict";F();pp();Cb=require("linkedom");Ji();W();Dt();mp();ve();Ma();oe();ds();$r=P("worker-appium"),bp=class extends Mt{initPlayer(t){return new Ds(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,i,n){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(n.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}=i,l=await Et.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:n,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a,customCapabilities:t.customCapabilities},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Et.lockDevice(n,this.options.deviceUdid),h=await fb(f)):h=await mb(f),$r.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:hb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await c.remote(h),this.device=await Et.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),$r.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw $r.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=ee(),i=async()=>{try{await t.getOrientation()}catch(n){$r.error("failed to keep appium session alive",{err:n}),r!=null&&r.AppiumSessionTerminatedError&&n instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(i,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&Jf(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){$r.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:i,type:n}=this.options.gridData;return n===N.TESTIM_TDC?`https://${t}:${r}/v0/${i}/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:i,path:n}=this.activeSession.options;if(t&&r&&i&&n)return`${t}://${r}:${i}${n}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:i,AppiumApi:n,localAssetService:o}=ee(),{sessionPlayer:a}=r,c=i||"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:v,hostname:b,port:T,path:w}=await Et.getTDCDeviceConnection(this.options.gridData,y);d=`${v}://${b}:${T}${w}`}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 n(d,this.activeSession.sessionId,Cb.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((b,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:b,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw $r.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 $r.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:test"}}});var $a,Ob=I(()=>{"use strict";F();$i();Y();$a=class{constructor(e){this.id=e;this.driver=new _r}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof ce&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function _b(){let s=await Promise.any(mI.map(async e=>{try{return await we(e)}catch{return null}}));return s==null?void 0:s.ip}var mI,Wa,Va=I(()=>{"use strict";He();mI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];Wa=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var Lb,Ga,Db=I(()=>{"use strict";Lb=R(require("ws"));F();Va();Ga=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=Wa({timeout:e}),r=new Lb.default(this._cdpUrl,t),i=Qt(o=>{r.once("open",o)}),n=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([i,n]).then(()=>r),this._cdpWs}onCDPMessage(e){var i;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)):(i=t.result.exceptionDetails)!=null&&i.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 i=await this.initCDPWebsocket();this._lastWsId||=0;let n=this._lastWsId++,o=new Promise((c,l)=>{this._cdpCallbacks.set(n,{resolve:c,reject:l})}),a={method:e,params:t,id:n};return r&&Object.assign(a,{sessionId:r}),i.send(JSON.stringify(a)),o}}});var qa,Tp,Ha,Nb=I(()=>{"use strict";F();qa=R(require("chrome-launcher"));Fo();Db();Pi();Tp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ga}async init(e){var h,g,y,v;let{browserOptions:t,testName:r,testRunConfig:i,gridInfo:n,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}=e,m=Mo({browserOptions:t,testName:r,testRunConfig:i,gridInfo:n,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((v=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:v.args)??[],...qa.Launcher.defaultFlags().filter(b=>b!=="--disable-extensions")];this.chrome=await qa.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 Sr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),ms(()=>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}},Ha=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new Tp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var wp={};z(wp,{WorkerExtension:()=>an});function fI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Mb(s){return fI(s)?s:new Error(s)}var tt,an,za=I(()=>{"use strict";We();Y();Ji();F();W();Dt();oe();Ob();Nb();ut();tt=P("worker-ext"),an=class extends Mt{initPlayer(){return this.options.useChromeLauncher?new Ha(this.id):new $a(this.id)}async _getBrowserOnce(e,t,r,i){var o;let{driver:n}=r;try{return await n.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,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:K.EXTENSION})}catch(a){throw tt.error("failed to get browser",{err:a,gridInfo:i,whitelistedPublicIp:io(),initializedFromCache:no(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,i){return Z.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,i)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var n;let i=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${i}`),"browserstack"in this.options&&((n=this.options.browserstack)!=null&&n["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:i,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:i,testId:n}=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 ce))throw u;return tt.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 tt.error("error from driver.url",{err:f,testResultId:r,executionId:i,testId:n,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 tt.warn("failed to run test via CDP",{err:y}),y}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let b=function(w){e.onCompletedCleanup(),tt.warn("on browser closed error detected",{err:w,testResultId:r,executionId:i,testId:n}),m.unregisterToClosedBrowser(b),m.unregisterToKeepAliveFailed(T),w.type=Kr.BROWSER_CLOSED,v.abort(w)},T=function(w){m.unregisterToClosedBrowser(b),m.unregisterToKeepAliveFailed(T),tt.warn("on keep alive failed error detected",{err:w,testResultId:r,executionId:i,testId:n}),w.type=Kr.KEEP_ALIVE_FAILED,v.abort(w)};var f=b,h=T;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(w){if(!(w instanceof ce))throw w;tt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:i,testId:n,...u}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let v=new AbortController;m.registerToClosedBrowser(b),m.registerToKeepAliveFailed(T);try{let w=le(e.onCompleted(),this.testRunTimeout,Pe.TEST_COMPLETE_TIMEOUT_MSG),E=await Rc(w,v.signal);m.unregisterToClosedBrowser(b),m.unregisterToKeepAliveFailed(T);try{await this.updateTestStatusOnGrid(m,Boolean(E.success),E.reason)}catch(B){tt.error("Could not update the grid about the test status",{err:B})}m.isAlive()||(tt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),E.gridIssues="could not validate grid is alive");let A=m.maxKeepAliveGap();return A>=3e4&&(tt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),E.keepAliveIssue=A),{...E,...e.seleniumPerfStats.getStats()}}catch(w){throw tt.warn("timeout wait until test completed",{err:w,testResultId:r,executionId:i,testId:n}),Mb(w)}finally{m.unregisterToClosedBrowser(b),m.unregisterToKeepAliveFailed(T)}}catch(y){throw tt.warn("failed to start url",{err:y}),Mb(y)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await l()}catch(d){throw tt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Sp={};z(Sp,{WorkerExtensionSingleBrowser:()=>vp});var gI,hI,vp,Ep=I(()=>{"use strict";We();F();W();Uu();Dt();za();gI=P("base-worker"),hI=500,vp=class extends an{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Ki(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,i,n){return Z.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,i,n)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(gI.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,i){let n=this.handleQuarantine(t);if(n)return n;M("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,i,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 pe(hI)}}});var Ip,Ka,Fb=I(()=>{"use strict";$i();ae();We();xl();ut();Tu();Y();W();oe();kh();Ko();Ip=P("worker-manager"),Ka=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 i=this.workerUniqueIds[t%this.parallelCount],n=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,n),n.id=t,n.uniqueId=i,n.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case K.SELENIUM:return(await Promise.resolve().then(()=>(ip(),sp))).WorkerSelenium;case K.APPIUM:return t?(await Promise.resolve().then(()=>(Ab(),xb))).WorkerLocalTma:(await Promise.resolve().then(()=>(kb(),Pb))).WorkerAppium;default:return Wi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Ep(),Sp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(za(),wp))).WorkerExtension}else switch(r){case(Mr.find(i=>i===r)&&Wi.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Ep(),Sp))).WorkerExtensionSingleBrowser;case Mr.find(i=>i===r):return(await Promise.resolve().then(()=>(za(),wp))).WorkerExtension;case zi.find(i=>i===r):return(await Promise.resolve().then(()=>(ip(),sp))).WorkerSelenium;default:throw new x(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],i=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return M("before new Worker",r.mode),new i(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,i,n,o,a,c){if(e&&e.length===0)return;let l=!1,d=0,m=(u,f)=>new Promise(h=>{var J,xe,Te,fr,k,L,$,X;let g=n.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new zo(r,i,e,n,o,t),this.combinedTestResults={};let v=((J=n.company)==null?void 0:J.ucid)||"",b=(xe=n.company)==null?void 0:xe.companyId,T=(Te=n.company)==null?void 0:Te.name,w=n.source||"cli",E=n.user,A=(fr=n.company)==null?void 0:fr.planType,_=(k=n.company)==null?void 0:k.isStartUp,B=(L=n.projectData)==null?void 0:L.name,V=($=n.projectData)==null?void 0:$.type,S=n.lightweightMode,C=(X=n.gridData)==null?void 0:X.type,D=(De,At,Se,dc,mn,mc)=>(d++,_f({executionId:r,projectId:g,testId:At,resultId:Se,ucid:v,companyId:b,companyName:T,projectName:B,companyPlan:A,source:w,user:E,lightweightMode:S,isStartUp:_,projectType:V,appSource:mc,gridType:C}),t.testStartAndReport(De,r,Se,dc,mn)),j=async(De,At,Se,dc,mn,mc)=>{var Td,wd,vd;d--;let rt={...(S==null?void 0:S.onlyTestIdsNoSuite)&&{show:!0},...Se.seleniumStats&&{seleniumStats:Se.seleniumStats},...Se.gridIssues&&{gridIssues:Se.gridIssues},...Se.keepAliveIssue&&{keepAliveIssue:Se.keepAliveIssue},...n.host&&{gridHost:n.host}};if(Se.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(Se.seleniumPerfMarks),delete Se.seleniumPerfMarks),n.grid||n.gridId?(rt.gridName=n.grid||((Td=n.gridData)==null?void 0:Td.name),rt.gridType=(wd=n.gridData)==null?void 0:wd.type,rt.gridProvider=(vd=n.gridData)==null?void 0:vd.provider):n.localTmaUrl?(rt.gridName="local-tma-from-options",rt.gridType="local-tma"):n.useLocalChromeDriver?(rt.gridName="local-chrome-driver-from-options",rt.gridType="local-chrome"):n.useChromeLauncher?(rt.gridName="chrome-launcher-from-options",rt.gridType="local-chrome"):n.browserstack?rt.gridName="browserstack-from-options":n.saucelabs&&(rt.gridName="saucelabs-from-options"),await t.testEndAndReport(De,Se,r,dc,mn,rt).catch(QT=>Ip.error("testEndAndReport threw an error",{err:QT})),mn)return;this.combinedTestResults[Se.resultId]=Se,Lf({executionId:r,projectId:g,testId:At,resultId:Se.resultId,result:Se,ucid:v,companyId:b,companyName:T,projectName:B,companyPlan:A,source:w,user:E,lightweightMode:S,logger:Ip,isStartUp:_,projectType:V,appSource:mc}),c&&!Se.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},H=(De,At)=>{this.combinedTestResults[At.resultId]=At,t.onTestIgnored(De,At.resultId),d--,(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},G=(De,At)=>t.onGridSlot(De,At);for(n.userData={loginData:{...xr(),refreshToken:ro(),authData:xr(),token:u,userAccessKey:f},projectId:n.project,company:n.company,servicesUrl:he()},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(n,this.customExtensionLocalLocation,r,D,j,G,H)});try{let u=await _t(),f=await so(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),l)throw new Xt;return h}catch(u){throw Ip.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var cn,Ub,Ja,Rp,xp,Wr,Ap=I(()=>{"use strict";cn=R(require("lodash"));F();W();ae();oe();We();os();Rl();xl();ge();Ub=require("uuid");Mf();F();Dt();wg();Y();Fb();de();Ko();({CLI_MODE:Ja}=Wt),Rp=P("test-plan-runner"),xp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return xp._id}async runTestAllPhases(e,t,r,i,n,o,a,c){let l={},d=new Ka(this.customExtensionLocalLocation),m=async()=>{let g=n.beforeParallel||1,y=!0,v=await d.runTests(e,c,o,a,n,i,g,y);Object.assign(l,v)},u=async()=>{let g=Rn||n.parallel,y=!1;M("right before this.workerManager.runTests");let v=await d.runTests(t,c,o,a,n,i,g,y);M("right after this.workerManager.runTests"),Object.assign(l,v)},f=async()=>{let g=n.afterParallel||1,y=!1,v=await d.runTests(r,c,o,a,n,i,g,y);Object.assign(l,v)};Df({executionId:o,projectId:n.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(Rp.error("error running test plan",{err:g}),g instanceof Xt)return c.markAllQueuedTests(o,fe.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,v,b,T;if((y=n.lightweightMode)!=null&&y.disablePixelValidation)return;if(n.mode===Ja.SELENIUM){let[{getSessionPlayer:w},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(ve(),or)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=w();await A.closeBatch(o,E);return}let g;try{if(!((T=(b=(v=n.company)==null?void 0:v.activePlan)==null?void 0:b.premiumFeatures)!=null&&T.applitools)||(g=await Op(n.project),cn.default.isEmpty(g)||!o))return;let{runKey:w,url:E}=g,A=require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}),_=1e4;await le(A.closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:w}}),_)}catch{}}}async runTestPlan(e,t,r,i,n,o,a,c){var T,w,E;let l=se(),d=i.project;Zd(l),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new xo(m,i,o,a),f=cn.default.chain(m).map(A=>{var _;return((_=A.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(T=i.lightweightMode)!=null&&T.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(w=i.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,d,this.startTime,n,g);M("before testListInfoPromise");let v=await y;(E=i.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Z.onTestPlanStarted(v.beforeTests,v.tests,v.afterTests,n,l,c,h),M("before runTestAllPhases");let b=await this.runTestAllPhases(v.beforeTests,v.tests,v.afterTests,a,i,l,n||"All Tests",u);return M("before executionEnd"),await u.executionEnd(l),M("after executionEnd"),{results:b,executionId:l,testPlanName:n,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(ue.colorString(ue.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await Cp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await Pp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){Rp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return cn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let i={},n={},o=e.project,a={testPlans:[],testPlansData:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await ie(e.testPlanIds,async d=>{let m=await ln(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 ie(e.testPlan,async d=>{let m=await ln(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 ln(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!==Ja.APPIUM&&await Mu(e,r(l)),await ie(c,async d=>{var h;let m=d.testPlanId;i[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 wf(e,d);let f=u.overrideExecutionName||d.name;return await ie(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),i[m][y.executionId]=y.results;let v=Object.keys(i[m]).map(E=>({executionId:E,status:Nu(i[m][E])})),b=Object.keys(i[m]).map(E=>i[m][E]).reduce((E,A)=>Object.assign(E,A),{}),T=Nu(b);Object.assign(n,b);let w=T?v[0].executionId:v.find(E=>!E.status).executionId;return await kp(o,m,{success:T,executions:v,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var c;Rp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await _h(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 i=r;if(e.rerunFailedByRunId&&!i.runName){if(!i.runExists)throw new x("Invalid run ID - no such run.");i.runName===""&&(i.runName=`rerun-${e.rerunFailedByRunId}`)}let n=e.overrideExecutionName||i.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===Ja.APPIUM&&(a=await nn({appId:e.appId,projectId:e.project})),await ie(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!==Ja.APPIUM&&await Mu(e,l),M("right before runTestPlan");let d=await this.runTestPlan([],l,[],e,n,null,t,o);return M("right after runTestPlan"),await Z.onTestPlanFinished(d.results,n,this.startTime,d.executionId,o),d})}async run(e){let t=vi(),r=[];await this.reportTestRunnerStarted(e.project,e),ti(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let i=cn.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(i),M("right after onAllTestPlansFinished"),i.map(n=>n.results).reduce((n,o)=>Object.assign(n,o),{})}},Wr=xp;Wr._id=(0,Ub.v4)()});var ke={};z(ke,{addTestRetry:()=>nu,clearTestResult:()=>Lu,deleteCloudflareTunnel:()=>jp,fetchLambdatestConfig:()=>cu,fixGridAppIDStructure:()=>ap,forceUpdateCloudflareTunnelRoutes:()=>Bp,getAllGrids:()=>Il,getAppDetails:()=>nn,getApplitoolsIntegrationData:()=>Op,getBrowserStackSessionMetaData:()=>xI,getCloudflareTunnel:()=>Up,getCustomCapabilitiesByName:()=>Wp,getEditorUrl:()=>EI,getFileUrl:()=>Dp,getGridSlot:()=>El,getHybridGridProvider:()=>Sl,getLabFeaturesByProjectId:()=>wu,getMobileDevicesFromGrid:()=>on,getRealData:()=>Ql,getS3Artifact:()=>_i,getS3ArtifactText:()=>Yl,getSuiteTestList:()=>Fu,getTestPlan:()=>SI,getTestPlanTestList:()=>ln,getTestResults:()=>Nr,getUsageForCurrentBillingPeriod:()=>Mp,initializeUserWithAuth:()=>Fp,isTestResultCompleted:()=>_u,keepAliveCompanySlots:()=>Jl,keepAliveGrid:()=>wl,loadSfdcCredential:()=>Np,loadTest:()=>Hi,releaseCompanySlot:()=>zl,releaseGridSlot:()=>vl,reportExecutionFinished:()=>Ao,reportExecutionStarted:()=>iu,reportRunnerFinished:()=>Pp,reportRunnerStarted:()=>Cp,requestCompanySlot:()=>ql,saveRemoteStep:()=>Su,saveTestPlanResult:()=>kp,updateCompanySlot:()=>Kl,updateExecutionTests:()=>su,updateRemoteRunFailure:()=>$p,updateTestDataArtifact:()=>Co,updateTestResult:()=>ea,updateTestStatus:()=>Pr,uploadAppToGrid:()=>op,uploadRunDataArtifact:()=>Du,validateUserAccessKey:()=>bl});async function Ns(){let s=await _t();if(!s)throw new Error("Failed to get token from server");return{[Wc]:Wr.id,Authorization:`Bearer ${s}`}}async function Ae({url:s,body:e,headers:t={},timeout:r,retry:i}){let n=await Ns(),o={...t,...n};return Ge({url:`${he()}${s||""}`,body:e,headers:o,timeout:r,retry:i})}async function wI(s,e,t,r={},i=void 0){let n=await Ns(),o={...r,...n};return await Ys(`${he()}${s||""}`,e,t,o,i)}async function un(s,e){let t=await Ns();return await kc(`${he()}${s||""}`,e,t)}async function jb(s,e){let t=await Ns();return await Xs(`${he()}${s||""}`,e,t)}async function vI(s,e){let t=await Ns();return await Pc(`${he()}${s||""}`,e||void 0,t)}async function Re(s,e,t,r){let i=await Ns();return await we(`${he()}${s||""}`,e||void 0,i,r,t)}function _i(s,e){return(0,te.default)(()=>Re(`/storage${s}`,null,{isBinary:!0},e),{retries:re,factor:1})}function Dp(s,e){return(0,te.default)(()=>Re(`/files/fileUrl?${s}`,null,{isBinary:!0},e),{retries:re,factor:1})}function Yl(s){return(0,te.default)(()=>vI(`/storage${s}`))}async function Cp(s,e){return await Ae({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function Pp(s){return await jb("/test-runner",{projectId:s})}async function SI(s,e){let t=i=>i===null?[]:typeof i=="string"&&JSON.parse(i)||i;return(await(0,te.default)(()=>Re("/testPlan",{projectId:s,name:e.join(",")}),{retries:re,factor:1})).map(({testConfigIds:i,beforeAllLabels:n,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(i),beforeAllLabels:t(n),testLabels:t(o),afterAllLabels:t(a)}))}async function Np({branch:s,projectId:e}){let t=await(0,te.default)(()=>Re(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:re,factor:1});return t==null?void 0:t.sfdcCredential}function Hi({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:i=!0}){return(0,te.default)(()=>Re(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:i}),{retries:re,factor:1})}function kp(s,e,t){return(0,te.default)(()=>Ae({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:re,factor:1})}function Pr(s,e,t,r,i,n,o=re){return(0,te.default)(()=>un("/result/run/test",{runId:e,testId:t,resultId:r,status:i,projectId:s,runnerVersion:yI,...n}),{retries:o,factor:1})}function su(s,e,t,r,i,n,o,a){return(0,te.default)(()=>un("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:i,startTime:n,endTime:o,projectId:a}),{retries:re,factor:1})}async function iu({executionId:s,projectId:e,labels:t,startTime:r,executions:i,config:n,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(lo(),Pf));return Ae({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:i,status:"RUNNING",config:n,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:c,isLocalRun:l}},retry:3})}function Ao(s,e,t,r,i={},n=void 0,o=void 0){let a=Date.now();return(0,te.default)(()=>un("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:i,remoteRunId:n,resultExtraData:o}),{retries:re,factor:1})}async function ln(s,e,t,r,i){return(0,te.default)(()=>Ae({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:i},timeout:12e4}),{retries:re,factor:1})}function Fu({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:i,suiteNames:n,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}){return(0,te.default)(()=>Ae({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:i,suiteNames:n,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}}),{retries:re,factor:1})}async function nn({appId:s,projectId:e}){try{return await(0,te.default)(()=>Re(`/mobile-app/app/${s}?projectId=${e}`),{retries:re,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function Mp(s){try{return await(0,te.default)(()=>Re(`/plan/project/${s}/usage-current-billing-period`),{retries:re,factor:1})}catch(e){Ft.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function _u(s,e,t){return(0,te.default)(()=>Re(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:re,factor:1})}function Nr(s,e,t,r){return(0,te.default)(()=>Re(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:re,factor:1})}function wl(s,e){return Ae({url:`/grid/keep-alive?reqId=${se()}`,body:{projectId:s,slots:e},timeout:1e4})}function vl(s,e,t,r,i){return Ae({url:`/grid/release?reqId=${se()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:i}})}function Sl(s){return Ae({url:"/grid/hybrid/provider",body:s})}function El(s){return(0,te.default)(()=>Re("/grid/grid-slot",{...s,reqId:se()}),{retries:re,factor:1})}async function Fp({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:i,publicIp:n,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d}){var m,u;try{return await(0,te.default)(()=>Ge({url:`${he()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:i,publicIp:n,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d},timeout:6e4}),{retries:re,factor:1})}catch(f){if(Ft.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(_p.default[y](_p.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Ft.error("Error parsing error message from server",f)}throw f}}async function EI(){if(st)return{editorUrl:st};try{return await(0,te.default)(()=>Re("/system-info/editor-url"),{retries:re,onFailedAttempt:s=>{if(s.attemptNumber>=re)throw s},factor:1})}catch(s){return Ft.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Il(s){return(0,te.default)(()=>Re("/grid",{companyId:s}),{retries:re,factor:1})}function Ql(s,e,t){return(0,te.default)(()=>Re(`/real-data/${e}?${t}&projectId=${s}`),{retries:re,factor:1})}function ea(s,e,t,r,i){return(0,te.default)(()=>Ae({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:i}}),{retries:re,factor:1})}function Lu(s,e,t,r){return(0,te.default)(()=>Ae({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:re,factor:1})}function Su(s,e,t,r){return(0,te.default)(()=>Ae({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:re,factor:1})}function II(s){return s.startsWith("/")?s:`/${s}`}function RI(s,e,t){let r=II(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function $b(s,e,t,r,i,n="application/octet-stream"){let o=null;n==="application/json"&&(o=".json");let a=`${i}_${se()}${o||""}`,c=`${e}/${t}/${a}`,l=RI(c,TI,s),d=Buffer.from(Bb.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,te.default)(()=>wI(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:re,factor:1}),l}function nu({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:i,previousTestResultId:n,testResult:o}){return(0,te.default)(()=>Ae({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:i,previousTestResultId:n,testId:t,runId:e,testResult:o}}),{retries:re,factor:1})}async function Op(s){try{return await Re(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Ft.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Up(s,e){try{return await un("/tunnel",{companyId:s,routes:e})}catch(t){return Ft.warn("could'nt get tunnel.",{err:t}),{}}}async function Bp(s,e){try{return await Ae({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Ft.warn("could'nt get tunnel.",{err:t});return}}async function jp(s,e){try{return await jb(`/tunnel/${e}`,{companyId:s})}catch(t){Ft.warn("could'nt get tunnel.",{err:t});return}}function $p(s){return Ge({url:`${he()}/result/remoteRunFailure`,body:s})}async function on({projectId:s,projectType:e,gridId:t,companyId:r,selectors:i}){let n=`${bI}/mobileDevices/${t}/${r}?projectType=${e}`;n=i?`${n}&selectors=${encodeURIComponent(i)}`:n;try{return await(0,te.default)(()=>Re(n,{projectId:s}),{retries:re,factor:1})}catch(o){return Ft.warn("could'nt get devices from grid.",{err:o}),null}}async function op({projectId:s,gridId:e,app:t,timeout:r}){return(0,te.default)(()=>Ae({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:re,factor:1})}async function ap(s){return(0,te.default)(()=>Ae({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:re,factor:1})}async function ql(s,e){return(0,te.default)(()=>Ae({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:re,factor:1})}async function zl(s,e,t){return(0,te.default)(()=>Ae({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:re,factor:1})}async function Kl(s,e,t){return(0,te.default)(()=>un("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:re,factor:1})}function Jl(s,e,t){return Ae({url:`/slot-management/keep-alive?reqId=${se()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function xI(s,e){return await we(`${Gs}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function bl(s){try{return await Re("/v2/project/validateUserAccessKey",s),!0}catch(e){return Ft.error("error validating user access key",{error:e}),!1}}async function Wp(s,e){let[t]=await Re("/capabilities?",{projectId:s,name:e});return t}var _p,pr,Bb,te,Lp,yI,Ft,re,bI,TI,cu,wu,Du,Co,ge=I(()=>{"use strict";_p=R(require("chalk")),pr=R(require("lodash")),Bb=R(require("pako"));F();ae();oe();He();ut();te=R(require("p-retry")),Lp=R(require("object-hash"));Y();W();Ap();yI=it(),Ft=P("testim service api"),re=3,bI="/grid",TI="test-result-artifacts";cu=async(s,e)=>(0,te.default)(()=>Re("/grid/lt/config",{companyId:s,...e&&{projectId:e}}),{retries:re,factor:1}),wu=async s=>(0,te.default)(()=>Re(`/labFeature/v2/project/${s}`),{retries:re,factor:1});Du=pr.memoize(async(s,e,t,r)=>{if(!pr.isEmpty(r))return await $b(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Lp.default)(r)}:${e}:${t}`),Co=pr.memoize(async(s,e,t,r,i)=>!r||pr.isEmpty(r)?void 0:await $b(s,e,t,JSON.stringify((()=>{let o=pr.clone(r);if(i!=null&&i.hiddenParams){let a=i.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:Bc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Lp.default)(r)}:${e}:${t}`)});function Xa(){return it()}var Vp=I(()=>{"use strict";F()});function PI(s){K.EXTENSION!==s&&process.nextTick(()=>{try{(ve(),ze(or)).getSessionPlayer()}catch{}})}function kI(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let i=r.color||"yellow",n=r.bgColor||"bgBlack";console.log(Gp.default[n](Gp.default[i](r.text)))})}function OI(s,e){let{serviceUrl:t}=s;Hs(t),Ot(async()=>s,Jr.CACHE_FN_NAME,Jr.TTL,{serviceUrl:t})(),Ut.setRegion(Eg[hs(e)])}async function pn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:i,useLocalChromeDriver:n,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,d=Boolean(i==null?void 0:i.general),m=Boolean(n||o),u=d?CI:AI,f=Xa(),h=Mc(),g=await zm(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await _b()}catch(T){Wb.error("failed to get public ip",T)}let v=!0;M("before initializeUserWithAuth");let b=await Ot(async()=>(PI(a),v=!1,await Fp({projectId:e,token:t,branchName:s.branch,lightweightMode:i,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 kI(b),OI(b.clientConfig,e),s.publicIps=[b.clientPublicIp],M("after initializeUserWithAuth"),y&&b.clientPublicIp&&b.clientPublicIp!==y&&(Wb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:b.clientPublicIp}),s.publicIps.push(y)),ff(b.authData,{projectId:e,token:t,userAccessKey:r,publicIp:b.clientPublicIp,initializedFromCache:v}),b}var Gp,Wb,AI,CI,Vb=I(()=>{"use strict";Gp=R(require("chalk"));We();ge();er();ut();Va();oe();W();de();Vp();F();is();ae();ko();Wb=P("initializeUserWithAuth"),AI=1e3*60*5,CI=1e3*60*60*10});async function qb(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await to():s.chromeBinaryLocation,e=li({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!==K.EXTENSION&&await Ir(s.playerLocation,s.canary),s.mode!==K.SELENIUM&&s.mode!==K.APPIUM&&!s.ext&&await cl(s.extensionLocation);let t;if(s.installCustomExtension){let i=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await al(s.installCustomExtension,i)}return await e,t}async function zb(s){var o;_I.info("prepare MockNetwork",{location:s});let e=await Dc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Gb*1e6)throw new Error(`${Hp} exceeded ${Gb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Hp} cannot be parsed.${Ya.EOL}${a}`)}let i=new Hb.default;if(!i.validate(Jc,r)){let a=(o=i.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Ya.EOL);throw new Error(`${Hp} is malformed.${Ya.EOL}${a}`)}return r.entries}var Ya,Hb,Gb,Hp,_I,qp=I(()=>{"use strict";Ya=R(require("node:os"));F();xm();pi();Hb=R(require("ajv"));oe();dl();W();Vb();Gb=1,Hp="JSON file supplied to --mock-network-pattern",_I=P("prepare runner")});function Qb(s){return s.start&&as(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Zb(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new x("Agent port is not number");let t=Po(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 eT=I(()=>{"use strict";Mi();cs();Y()});var Ms,Xp,tT=I(()=>{"use strict";Ms="SECRETS",Xp={get secretsKey(){return Ms},get proxySecrets(){return new Proxy({},{get(s,e){return`${Ms}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[Ms]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(Ms):JSON.stringify(s).includes(Ms)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${Ms}\\.\\w+`,"g"));return r==null||r.map(i=>{let n=i.split(".")[1];n&&e.add(n)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^${r}\\.(\\w+)$`),n=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(i);if(l){let d=l[1];o[c]=e[d]??a}}else typeof a=="object"&&a!==null&&n(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(i);if(l){let d=l[1];o[a]=e[d]??c}}else typeof c=="object"&&c!==null&&n(c)})};n(s)}}});var td={};z(td,{doLogin:()=>ed,getProjectId:()=>UI,getToken:()=>BI});async function UI(){return iT("projectId")}async function BI(){return iT("token")}function sT(s,e){return Promise.race([s,pe(e).then(()=>{throw new ce("timeout")})])}async function jI(){let s=(await import("express")).default(),e=async function(){return sT(new Promise(i=>{s.get("/loginInfo",(n,o)=>{i(JSON.parse(Buffer.from(n.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,i)=>{let n=s.listen(42543,o=>{o&&i(o),r(n.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),ke)),{editorUrl:i}=await r();vo(`${i}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${st||yr}`)}return await e}async function ed({overwriteExisting:s=!0,projects:e=null}={}){let t=Yp.homedir(),r=Qp.join(t,".testim");if(await ye(r)&&!s)return;let n={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await sT(jI(),62e3).catch(()=>null)),e!=null&&e.token){n.token=e.token,n.projectId=e.projectId,c.succeed(),await rT(r,n);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}))});n.token=l.project.ci.token,n.projectId=l.project.id,await rT(r,n);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function rT(s,e){await Zp.promises.writeFile(s,Za.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function iT(s){let e=Yp.homedir(),t=Qp.join(e,".testim"),r=await ye(t),i={};if(r)try{i=Za.parse((await Zp.promises.readFile(t)).toString())}catch{}return i||={},i[s]}var Yp,Qp,Za,Zp,ec=I(()=>{"use strict";Yp=R(require("os")),Qp=R(require("path")),Za=R(require("yaml"));F();Zp=require("fs");Y();Wl();ae()});var mT={};z(mT,{process:()=>JI,program:()=>p});var sd,lT,tc,uT,xt,_e,pT,$I,Ue,WI,nd,VI,GI,oT,dT,dn,id,rc,od,rd,Rt,aT,HI,qI,p,zI,KI,cT,JI,fT=I(()=>{"use strict";sd=R(require("ms")),lT=R(require("chalk")),tc=R(require("node:fs")),uT=R(require("node:url")),xt=R(require("lodash")),_e=R(require("node:path"));F();Mi();eT();er();pT=require("commander");oe();Y();Vr();F();de();tT();Ko();ko();ae();lu();$I=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ue=(s,e)=>(e.push(s),e),WI=s=>(e,t)=>{if(t!==void 0)throw new x(`The ${s} flag can only be specified once.`);return e},nd=new pT.Command,VI=s=>s.split(","),GI=(s,e)=>!s||s.length===0?e:s,oT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],dT=()=>{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 i(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function n(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")}nd.help(g=>g.split(`
405
405
  `).filter(v=>!t(v)&&!e(v)&&!s(v)&&!r(v)&&!i(v)&&!a(v)&&!o(v)&&!n(v)&&!c(v)&&!l(v)&&!d(v)&&!m(v)&&!u(v)&&!f(v)&&!h(v)).join(`
406
- `))},mn=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(dT.default.yellow(`
406
+ `))},dn=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(lT.default.yellow(`
407
407
  WARNING: ${s} is deprecated. ${t}
408
- `))},od=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:nc,argv:cd,exit:id,cwd:Rt}=global.process,uT={development:{usw2:{servicesUrl:"https://services.dev.testim.io"},euc1:{servicesUrl:"https://services-eu.dev.testim.io"}},staging:{usw2:{servicesUrl:"https://services.staging.testim.io"},euc1:{servicesUrl:"https://services-eu.staging.testim.io"}},production:{usw2:{servicesUrl:"https://services.testim.io"},euc1:{servicesUrl:"https://services-eu.prod.testim.io"}}},JI=async s=>{let e=Ts(s),t=await tl(Qr.CACHE_FN_NAME);if(t&&t.region===e){Hs(t.servicesUrl);return}let i=(uT[Vs]||uT.production)[e]||{servicesUrl:"https://services.testim.io"};nc.SERVICES_HOST||Hs(i.servicesUrl)},YI=new Set(["trace","debug","info","warn","error","silent"]);zc(cd,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));ad.description("Testim.io CLI").option("-h --help","output usage information",gT).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",zI).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(nc.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,nd.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,nd.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: ${od.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',qI("--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(cd);p=ad.opts(),XI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},QI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},pT=s=>{var r;if(!O.flags.secrets.isEnabled({projectId:p.project}))return;let t=ic.readFileSync(s);(r=Qp)!=null&&r.containsSecrets(t.toString())&&Qp.injectProxySecretsStoreToGlobal()},ZI=async()=>{var b,T,w,E,C,_,B,V;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={},i;if(!cd.slice(2).length)throw gT(),new zr;if(p.version){let S="Testim CLI Version: ";nc.npm_package_version&&(console.log(S,nc.npm_package_version),id(0));let A=it();A&&(console.log(S,A),id(0)),console.log("Could not find version, please check the package.json manually"),id(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&$m(),p.clearFileCache&&ns();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let S=_e.resolve(n);Bm(S)}if(p.usePrefechedData&&Wm(),p.playerRequirePath){let S=_e.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",S);let A=_e.join(S,"tsconfig.node.json"),j=require("ts-node").register({project:A,ignore:[/node_modules/,new RegExp(`^${xt.escapeRegExp(_e.relative(Rt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:j.config.options.paths,baseUrl:j.config.options.baseUrl}),(ve(),ze(or)).options.playerPath=S;let G=require("node:module"),J=G.prototype.require;G.prototype.require=function(Te){return Te==="rox-alias"?J.call(this,"rox-node"):Te==="canvas"?{}:J.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=ic.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(tT(p))return rT(p);try{let S={};p.configFile?(pT(p.configFile),S=require(_e.join(Rt(),p.configFile)).config):p.optionsFile&&(S=require(_e.join(Rt(),p.optionsFile))),S&&typeof S.then=="function"&&(S=await S),Object.keys(S).forEach(A=>{let N=HI(A);p[N]=KI(p[N],S[A])})}catch(S){throw S.message=`Unable to read options file: ${S.message}`,S}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=((b=p.testConfig)==null?void 0:b.length)||((T=p.testConfigId)==null?void 0:T.length),a=((w=p.testPlan)==null?void 0:w.length)||((E=p.testPlanId)==null?void 0:E.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{i=require(_e.join(Rt(),p.customCapabilitiesFile)),Lo(i)}catch(S){throw S instanceof x?S:new x(`Failed to parse custom capabilities file: ${S.message}`)}if(p.seleniumCapsFile){mn("--selenium-caps-file","--custom-capabilities-name or --custom-capabilities-file");try{r=require(_e.join(Rt(),p.seleniumCapsFile))}catch(S){throw new x(`Failed to parse selenium caps file file error: ${S.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(Rt(),p.chromeExtraPrefs))}catch(S){throw new x(`Failed to read/open chrome extra prefs file error: ${S.message}`)}if(p.chromeExtraArgs){let S=p.chromeExtraArgs.split(",");for(let A of S){let[N]=A.split("=");lT.includes(N)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(A),N==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${N}), allowed values: ${JSON.stringify(lT)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&pT(p.paramsFile),s={...s,...require(_e.join(Rt(),p.paramsFile))}}catch(S){throw new x(`Failed to read/open params file error: ${S.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(S){throw new x(`Failed to parse params string error: ${S.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&&(XI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions){mn("--sauce-options","--custom-capabilities-name or --custom-capabilities-file");try{let S=require(_e.join(Rt(),p.sauceOptions)),A=S.platformName&&["ios","android"].includes(S.platformName.toLowerCase());if(S.browserName){let j=S.browserName.toLowerCase();switch(j){case"microsoftedge":p.browser="edge";break;default:p.browser=j}}p.browser==="edge"&&parseFloat(S.version)>=79&&(p.browser="edge-chromium");let N=parseFloat(S.version)<50&&!["dev","beta"].includes(S.version);if(!A&&p.browser==="chrome"&&N)throw new x("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...S}}catch(S){throw new x(`Failed to parse saucelabs options file error: ${S.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&&(QI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions){mn("--browserstack-options","--custom-capabilities-name or --custom-capabilities-file");try{let S=require(_e.join(Rt(),p.browserstackOptions)),A=S.platform&&["mac","android"].includes(S.platform.toLowerCase());if(S.browserName&&(p.browser=S.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(S.browser_version)>=79&&(p.browser="edge-chromium"),!A&&parseFloat(S.browser_version)<50&&p.browser==="chrome")throw new x("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...S}}catch(S){throw new x(`Failed to parse browserstack options file error: ${S.message}`)}}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions){mn("--perfecto-options","--custom-capabilities-name or --custom-capabilities-file");try{let S=require(_e.join(Rt(),p.perfectoOptions)),A={location:"US East",securityToken:p.perfectoToken};p.perfecto={...A,...S}}catch(S){throw new x(`Failed to parse perfecto options file error: ${S.message}`)}}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let S=require(_e.join(Rt(),p.testobjectOptions)),A={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...A,...S}}catch(S){throw new x(`Failed to parse test object options file error: ${S.message}`)}let l={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId,testStage:p.sealightsTestStage}};if(p.testOptimization=l,!p.project){let A=await(await Promise.resolve().then(()=>(sc(),sd))).getProjectId();if(A)p.project=A;else throw new x("missing project-id info, either --login to provide new credentials or use --project <project-id>")}JI(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 A=await(await Promise.resolve().then(()=>(sc(),sd))).getToken();if(A)p.token=A;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=S=>S<=0||!Number.isInteger(S);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&&![K.EXTENSION,K.SELENIUM,K.APPIUM].includes(p.mode))throw new x(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Fr,...Ki].includes(p.browser))throw new x(`browser ${p.browser} is not supported`);if(p.mode!==K.SELENIUM&&p.disableNativeEvents)throw new x("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!YI.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((V=p.host)!=null&&V.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=mT.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(A=>A.trim()).filter(Boolean);let S=p.resultLabel.filter(A=>A.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&Sr()&&p.resultLabel.unshift(Sr()),S.length)throw new x("A result label cannot exceed 250 characters")}let h=ko(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&&!xt.inRange(xt.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&&xt.difference(p.codeCoverageReporter,od).length){let S=xt.difference(p.codeCoverageReporter,od);throw new x(`invalid --code-coverage-reporter parameters ${S.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"},v=Object.keys(y).filter(S=>Boolean(p[S]));if([K.APPIUM,K.SELENIUM].includes(p.mode)&&v.length){let S=v.length>1?"are":"is";throw new x(`${v.map(A=>y[A]).join(" and ")} ${S} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let S=ic.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(S)}catch(S){throw new x(`failed to parse field file error: ${S.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(ei).includes(p.labelIntersectionOperand))throw new x(`The --label-intersection-operand flag must be one of the following values: ${Object.values(ei).join(", ")}`);if(p.labelIntersectionOperand&&xt.isEmpty(p.intersectWithLabel))throw new x("The --label-intersection-operand flag must be used together with the --intersect-with-label flag.");if(p.highSpeed&&(mn("--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 S={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"},A=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...S,...A}}catch(S){throw new x(`failed to parse lightweightMode settings error: ${S.message}`)}else p.turboMode&&![K.APPIUM,K.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&&[K.APPIUM,K.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"?Sr():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:i,customCapabilitiesName:p.customCapabilitiesName}}});var ld,eR,Fs,bT,TT,ud,wT,vT=I(()=>{"use strict";F();X();W();Oi();ld=P("testimNgrok"),eR=".whitelisted-ngrok.testim.io",Fs="",TT=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=`${se()}-${s.projectData.projectId}${eR}`);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 n=await(await mt("ngrok")).connect(r);s.tunnelUseHttpAddress&&n.startsWith("https://")?(ld.info("replace https to http"),Fs=n.replace("https://","http://")):Fs=n,s.tunnelDiagnostics&&ud(),s.baseUrl=Fs},ud=async(s=!0)=>{try{let t=(await mt("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),i=r.find(n=>n.public_url===Fs);console.log("ngrok stats",i),ld.info("ngrok stats",{tunnel:i})}catch(e){ld.error("error collecting ngrok stats",{err:e})}s&&(bT=setTimeout(()=>ud(),1e4))},wT=async s=>{if(!Fs)return;clearTimeout(bT),s.tunnelDiagnostics&&await ud(!1),await(await mt("ngrok")).disconnect(Fs)}});var mr,dd,ST,rR,sR,pd,oc,cc,ac,iR,ET,IT,RT=I(()=>{"use strict";mr=R(require("os")),dd=R(require("fs")),ST=R(require("child_process"));F();ge();rR="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",sR={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},pd=mr.tmpdir(),oc=`${pd}/cloudflared`,cc=null,ac=null,iR=async()=>{if(await ye(oc))return;let e=sR[mr.platform()+mr.arch()];if(!e)throw new Error(`tunnel on ${mr.platform()+mr.arch()} platform is not supported.`);let t=e.extract?pd+e.path:oc;await Ye(`${rR}/${e.path}`,t),e.extract&&await ct(t,pd),await dd.promises.chmod(oc,"755")},ET=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([jp(s.company.companyId,t),iR()]);cc=r._id,ac=ST.spawn(oc,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await $p(s.company.companyId,cc),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await dd.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},IT=async s=>{let e=[];return cc&&e.push(Wp(s.company.companyId,cc)),ac&&e.push(new Promise((t,r)=>{ac.on("close",i=>{i&&r(new Error(`tunnel process exited with code ${i}`)),t()}),ac.kill()})),await Promise.all(e)}});var md={};z(md,{connect:()=>uc,disconnect:()=>pc,serveTunneling:()=>aR});var lc,xT,CT,oR,uc,pc,aR,fd=I(()=>{"use strict";vT();ki();RT();ut();lc=R(require("ora"));W();ae();Do();xT=P("tunnel"),CT=s=>{var e;return[D.TESTIM_LAMBDATEST,D.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},oR=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===D.HYBRID&&s.gridData.tunnel==="cloudflare"},uc=async s=>{if(!s.tunnel)return;let e=Cr(),t;try{CT(s)?(t=(0,lc.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):oR(s)?(t=(0,lc.default)("Starting testim cloudflare tunnel...").start(),await ET(s)):(t=(0,lc.default)("Starting testim ngrok tunnel...").start(),await TT(s,e)),t.succeed()}catch(r){let i="Failed to start tunnel. Please contact support@testim.io";throw r.isInvalidCredsForLT&&(i="Could not connect to LambdaTest. Check your credentials and then try again."),xT.error("Failed to open tunnel",{err:r}),t==null||t.fail(i),new Error(r.isInvalidCredsForLT?`${i}
410
- ${r.stdoutResult}`:i)}},pc=async s=>{if(s.tunnel)try{CT(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await IT(s):await wT(s)}catch(e){let t="catch error - failed to close tunnel";throw xT.error(t,{err:e}),new Error(t)}},aR=async(s,e=new Promise(()=>{}))=>(await uc(s),hs(()=>pc(s)),await e)});var OT={};z(OT,{init:()=>_R,run:()=>AR});async function lR(s){let e=s.project,t=await Up(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"),us(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new qs}function pR(s,e){var n,o,a,c,l,d,m,u,f,h,g,y,v;let t=$n(e.activePlan),r=s.parallel;if(t==="free"&&r>PT)throw new x(`The free plan allows only ${PT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let b=(n=s.projectData)!=null&&n.type?uR[s.projectData.type]:void 0,T=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&b?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[b]:0;T&&r>T&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${T}).
408
+ `))},id=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:rc,argv:od,exit:rd,cwd:Rt}=global.process,aT={development:{usw2:{servicesUrl:"https://services.dev.testim.io"},euc1:{servicesUrl:"https://services-eu.dev.testim.io"}},staging:{usw2:{servicesUrl:"https://services.staging.testim.io"},euc1:{servicesUrl:"https://services-eu.staging.testim.io"}},production:{usw2:{servicesUrl:"https://services.testim.io"},euc1:{servicesUrl:"https://services-eu.prod.testim.io"}}},HI=async s=>{let e=hs(s),t=await Yc(Jr.CACHE_FN_NAME);if(t&&t.region===e){Hs(t.servicesUrl);return}let i=(aT[Vs]||aT.production)[e]||{servicesUrl:"https://services.testim.io"};rc.SERVICES_HOST||Hs(i.servicesUrl)},qI=new Set(["trace","debug","info","warn","error","silent"]);Vc(od,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));nd.description("Testim.io CLI").option("-h --help","output usage information",dT).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",VI).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(rc.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,sd.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,sd.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: ${id.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',WI("--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(od);p=nd.opts(),zI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},KI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},cT=s=>{var r;if(!O.flags.secrets.isEnabled({projectId:p.project}))return;let t=tc.readFileSync(s);(r=Xp)!=null&&r.containsSecrets(t.toString())&&Xp.injectProxySecretsStoreToGlobal()},JI=async()=>{var b,T,w,E,A,_,B,V;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={},i;if(!od.slice(2).length)throw dT(),new Gr;if(p.version){let S="Testim CLI Version: ";rc.npm_package_version&&(console.log(S,rc.npm_package_version),rd(0));let C=it();C&&(console.log(S,C),rd(0)),console.log("Could not find version, please check the package.json manually"),rd(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Um(),p.clearFileCache&&rs();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let S=_e.resolve(n);Mm(S)}if(p.usePrefechedData&&Bm(),p.playerRequirePath){let S=_e.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",S);let C=_e.join(S,"tsconfig.node.json"),j=require("ts-node").register({project:C,ignore:[/node_modules/,new RegExp(`^${xt.escapeRegExp(_e.relative(Rt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:j.config.options.paths,baseUrl:j.config.options.baseUrl}),(ve(),ze(or)).options.playerPath=S;let G=require("node:module"),J=G.prototype.require;G.prototype.require=function(Te){return Te==="rox-alias"?J.call(this,"rox-node"):Te==="canvas"?{}:J.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=tc.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(Qb(p))return Zb(p);try{let S={};p.configFile?(cT(p.configFile),S=require(_e.join(Rt(),p.configFile)).config):p.optionsFile&&(S=require(_e.join(Rt(),p.optionsFile))),S&&typeof S.then=="function"&&(S=await S),Object.keys(S).forEach(C=>{let D=$I(C);p[D]=GI(p[D],S[C])})}catch(S){throw S.message=`Unable to read options file: ${S.message}`,S}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=((b=p.testConfig)==null?void 0:b.length)||((T=p.testConfigId)==null?void 0:T.length),a=((w=p.testPlan)==null?void 0:w.length)||((E=p.testPlanId)==null?void 0:E.length),c=((A=p.suite)==null?void 0:A.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{i=require(_e.join(Rt(),p.customCapabilitiesFile)),Lo(i)}catch(S){throw S instanceof x?S:new x(`Failed to parse custom capabilities file: ${S.message}`)}if(p.seleniumCapsFile){dn("--selenium-caps-file","--custom-capabilities-name or --custom-capabilities-file");try{r=require(_e.join(Rt(),p.seleniumCapsFile))}catch(S){throw new x(`Failed to parse selenium caps file file error: ${S.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(Rt(),p.chromeExtraPrefs))}catch(S){throw new x(`Failed to read/open chrome extra prefs file error: ${S.message}`)}if(p.chromeExtraArgs){let S=p.chromeExtraArgs.split(",");for(let C of S){let[D]=C.split("=");oT.includes(D)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(C),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(oT)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&cT(p.paramsFile),s={...s,...require(_e.join(Rt(),p.paramsFile))}}catch(S){throw new x(`Failed to read/open params file error: ${S.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(S){throw new x(`Failed to parse params string error: ${S.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&&(zI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions){dn("--sauce-options","--custom-capabilities-name or --custom-capabilities-file");try{let S=require(_e.join(Rt(),p.sauceOptions)),C=S.platformName&&["ios","android"].includes(S.platformName.toLowerCase());if(S.browserName){let j=S.browserName.toLowerCase();switch(j){case"microsoftedge":p.browser="edge";break;default:p.browser=j}}p.browser==="edge"&&parseFloat(S.version)>=79&&(p.browser="edge-chromium");let D=parseFloat(S.version)<50&&!["dev","beta"].includes(S.version);if(!C&&p.browser==="chrome"&&D)throw new x("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...S}}catch(S){throw new x(`Failed to parse saucelabs options file error: ${S.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&&(KI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions){dn("--browserstack-options","--custom-capabilities-name or --custom-capabilities-file");try{let S=require(_e.join(Rt(),p.browserstackOptions)),C=S.platform&&["mac","android"].includes(S.platform.toLowerCase());if(S.browserName&&(p.browser=S.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(S.browser_version)>=79&&(p.browser="edge-chromium"),!C&&parseFloat(S.browser_version)<50&&p.browser==="chrome")throw new x("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...S}}catch(S){throw new x(`Failed to parse browserstack options file error: ${S.message}`)}}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions){dn("--perfecto-options","--custom-capabilities-name or --custom-capabilities-file");try{let S=require(_e.join(Rt(),p.perfectoOptions)),C={location:"US East",securityToken:p.perfectoToken};p.perfecto={...C,...S}}catch(S){throw new x(`Failed to parse perfecto options file error: ${S.message}`)}}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let S=require(_e.join(Rt(),p.testobjectOptions)),C={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...C,...S}}catch(S){throw new x(`Failed to parse test object options file error: ${S.message}`)}let l={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId,testStage:p.sealightsTestStage}};if(p.testOptimization=l,!p.project){let C=await(await Promise.resolve().then(()=>(ec(),td))).getProjectId();if(C)p.project=C;else throw new x("missing project-id info, either --login to provide new credentials or use --project <project-id>")}HI(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 C=await(await Promise.resolve().then(()=>(ec(),td))).getToken();if(C)p.token=C;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=S=>S<=0||!Number.isInteger(S);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&&![K.EXTENSION,K.SELENIUM,K.APPIUM].includes(p.mode))throw new x(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Mr,...zi].includes(p.browser))throw new x(`browser ${p.browser} is not supported`);if(p.mode!==K.SELENIUM&&p.disableNativeEvents)throw new x("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!qI.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((V=p.host)!=null&&V.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=uT.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(C=>C.trim()).filter(Boolean);let S=p.resultLabel.filter(C=>C.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&vr()&&p.resultLabel.unshift(vr()),S.length)throw new x("A result label cannot exceed 250 characters")}let h=Po(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&&!xt.inRange(xt.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&&xt.difference(p.codeCoverageReporter,id).length){let S=xt.difference(p.codeCoverageReporter,id);throw new x(`invalid --code-coverage-reporter parameters ${S.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"},v=Object.keys(y).filter(S=>Boolean(p[S]));if([K.APPIUM,K.SELENIUM].includes(p.mode)&&v.length){let S=v.length>1?"are":"is";throw new x(`${v.map(C=>y[C]).join(" and ")} ${S} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let S=tc.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(S)}catch(S){throw new x(`failed to parse field file error: ${S.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(Zs).includes(p.labelIntersectionOperand))throw new x(`The --label-intersection-operand flag must be one of the following values: ${Object.values(Zs).join(", ")}`);if(p.labelIntersectionOperand&&xt.isEmpty(p.intersectWithLabel))throw new x("The --label-intersection-operand flag must be used together with the --intersect-with-label flag.");if(p.highSpeed&&(dn("--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 S={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"},C=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...S,...C}}catch(S){throw new x(`failed to parse lightweightMode settings error: ${S.message}`)}else p.turboMode&&![K.APPIUM,K.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&&[K.APPIUM,K.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"?vr():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:i,customCapabilitiesName:p.customCapabilitiesName}}});var ad,XI,Fs,gT,hT,cd,yT,bT=I(()=>{"use strict";F();Y();W();ki();ad=P("testimNgrok"),XI=".whitelisted-ngrok.testim.io",Fs="",hT=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=`${se()}-${s.projectData.projectId}${XI}`);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 n=await(await mt("ngrok")).connect(r);s.tunnelUseHttpAddress&&n.startsWith("https://")?(ad.info("replace https to http"),Fs=n.replace("https://","http://")):Fs=n,s.tunnelDiagnostics&&cd(),s.baseUrl=Fs},cd=async(s=!0)=>{try{let t=(await mt("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),i=r.find(n=>n.public_url===Fs);console.log("ngrok stats",i),ad.info("ngrok stats",{tunnel:i})}catch(e){ad.error("error collecting ngrok stats",{err:e})}s&&(gT=setTimeout(()=>cd(),1e4))},yT=async s=>{if(!Fs)return;clearTimeout(gT),s.tunnelDiagnostics&&await cd(!1),await(await mt("ngrok")).disconnect(Fs)}});var dr,ud,TT,QI,ZI,ld,sc,nc,ic,eR,wT,vT,ST=I(()=>{"use strict";dr=R(require("os")),ud=R(require("fs")),TT=R(require("child_process"));F();ge();QI="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",ZI={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},ld=dr.tmpdir(),sc=`${ld}/cloudflared`,nc=null,ic=null,eR=async()=>{if(await ye(sc))return;let e=ZI[dr.platform()+dr.arch()];if(!e)throw new Error(`tunnel on ${dr.platform()+dr.arch()} platform is not supported.`);let t=e.extract?ld+e.path:sc;await Xe(`${QI}/${e.path}`,t),e.extract&&await ct(t,ld),await ud.promises.chmod(sc,"755")},wT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Up(s.company.companyId,t),eR()]);nc=r._id,ic=TT.spawn(sc,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Bp(s.company.companyId,nc),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await ud.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},vT=async s=>{let e=[];return nc&&e.push(jp(s.company.companyId,nc)),ic&&e.push(new Promise((t,r)=>{ic.on("close",i=>{i&&r(new Error(`tunnel process exited with code ${i}`)),t()}),ic.kill()})),await Promise.all(e)}});var pd={};z(pd,{connect:()=>ac,disconnect:()=>cc,serveTunneling:()=>sR});var oc,ET,IT,rR,ac,cc,sR,dd=I(()=>{"use strict";bT();Pi();ST();ut();oc=R(require("ora"));W();oe();_o();ET=P("tunnel"),IT=s=>{var e;return[N.TESTIM_LAMBDATEST,N.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},rR=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===N.HYBRID&&s.gridData.tunnel==="cloudflare"},ac=async s=>{if(!s.tunnel)return;let e=xr(),t;try{IT(s)?(t=(0,oc.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):rR(s)?(t=(0,oc.default)("Starting testim cloudflare tunnel...").start(),await wT(s)):(t=(0,oc.default)("Starting testim ngrok tunnel...").start(),await hT(s,e)),t.succeed()}catch(r){let i="Failed to start tunnel. Please contact support@testim.io";throw r.isInvalidCredsForLT&&(i="Could not connect to LambdaTest. Check your credentials and then try again."),ET.error("Failed to open tunnel",{err:r}),t==null||t.fail(i),new Error(r.isInvalidCredsForLT?`${i}
410
+ ${r.stdoutResult}`:i)}},cc=async s=>{if(s.tunnel)try{IT(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await vT(s):await yT(s)}catch(e){let t="catch error - failed to close tunnel";throw ET.error(t,{err:e}),new Error(t)}},sR=async(s,e=new Promise(()=>{}))=>(await ac(s),ms(()=>cc(s)),await e)});var CT={};z(CT,{init:()=>CR,run:()=>IR});async function nR(s){let e=s.project,t=await Mp(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"),as(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new qs}function aR(s,e){var n,o,a,c,l,d,m,u,f,h,g,y,v;let t=jn(e.activePlan),r=s.parallel;if(t==="free"&&r>xT)throw new x(`The free plan allows only ${xT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let b=(n=s.projectData)!=null&&n.type?oR[s.projectData.type]:void 0,T=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&b?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[b]:0;T&&r>T&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${T}).
411
411
  We'll use the maximum of ${T} for now. To use more, you can adjust your command or upgrade your plan.`),s.parallel=T);let w=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.tunnel;if(s.tunnel&&!w)throw new x("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let E=(m=(d=e.activePlan)==null?void 0:d.premiumFeatures)==null?void 0:m.runInTurboMode;s.lightweightMode&&!E&&(console.warn(`
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)===D.TESTIM_TVC){let b=e.tvcLicense.expireAt||1;if(Date.now()>b&&!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 T=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>T)throw new x(`Your license allows only ${T} 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)===D.TESTIM_TDC){let b=e.tdcLicense.expireAt||1;if(Date.now()>b)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 i=s.retentionDays;if(i){let b=(v=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:v.resultRetention;if(i>b)throw new x(`Retention days (${i}) cannot be greater than the company's retention days (${b}). Run aborted`)}if(Zt(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let b=e.tvcLicense,T=e.tdcLicense;if(b!=null&&b.isPaid||T!=null&&T.isPaid)return;let w=e==null?void 0:e.createdAt;if(new Date(w)<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 dR(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await lR(s)}catch(t){if([x,qs].some(r=>t instanceof r))throw t;gd.error("could not validate cli account",{err:t})}}function mR(s){let e=Cr();return Of({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 vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Ho(),Eh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(qo(),xh));r.init(s)}}function gR(s,e){let{branch:t,autoDetect:r}=s;if(Cf(e,r),!e&&!r)throw new x(`branch ${t} does not exist, run aborted.`)}async function hR(s,e){let{id:t,type:r}=e,n=kT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=Si();n&&(s.sfdcCredential=await Fp({projectId:t,branch:o}))}async function yR(s){if(!s.testDataFileName)return;let{testDataFileName:e}=s,t;try{t=(await Mp(`fileName=${e}&action=download&fileType=test-data&projectId=${s.project}`)).s3Url;let n=await(await fetch(t)).json();dt("test-data-file-used-in-cli",{projectId:s.project,testDataFileId:e,source:s.source}),s.testDataFileName=e,s.testDataString=n.testData}catch(r){let i=t?`, s3Url: ${t}`:"";throw new x(`Failed to read/open test data file error: ${r.message}${i}`)}}function bR(s,e){let{id:t,name:r,activePlan:i={}}=e,n=Boolean(i.isPoc),o=Boolean(i.isStartUp),a=$n(i);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<AT?AT:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(n),O.setIsStartUp(o),O.setPlanType(a),Dt.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:n,isStartUp:o,activePlan:i}}function TR(s,e){s.editorUrl=st||e}function wR(s,e){s.allGrids=e}function vR(s,e){s.authData=e}function SR(s,e){let{id:t,name:r,type:i,defaults:n}=e;O.setProjectId(t),O.setProjectType(i),s.projectData={projectId:t,type:i,name:r,defaults:n}}async function ER(s){var e;s.gridData=await If(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function IR(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function RR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(dt("user-override-file",t),s.mockNetworkRules=await Yb(s.overrideMappingFile))}async function xR(s){if(s.customCapabilitiesName){let e=await Gp(s.project,s.customCapabilitiesName);if(!e)throw new x(`"${s.customCapabilitiesName}" custom capabilities not found`);s.customCapabilities=e.capabilities}}async function CR(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:i,useChromeLauncher:n}=s;r||(s.source=i||n?"cli-local":"cli"),await dR(s),M("in runRunner before tunnel.connect"),await uc(s),M("in runRunner after tunnel.connect");let a=await new Hr(e).run(s);return M("before tunnel.disconnect"),await pc(s),await OR(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function PR(s){var e;Dt.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 b=e.tvcLicense.expireAt||1;if(Date.now()>b&&!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 T=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>T)throw new x(`Your license allows only ${T} 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 b=e.tdcLicense.expireAt||1;if(Date.now()>b)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 i=s.retentionDays;if(i){let b=(v=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:v.resultRetention;if(i>b)throw new x(`Retention days (${i}) cannot be greater than the company's retention days (${b}). Run aborted`)}if(Zt(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let b=e.tvcLicense,T=e.tdcLicense;if(b!=null&&b.isPaid||T!=null&&T.isPaid)return;let w=e==null?void 0:e.createdAt;if(new Date(w)<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 A=s.retries;A&&A>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function cR(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await nR(s)}catch(t){if([x,qs].some(r=>t instanceof r))throw t;md.error("could not validate cli account",{err:t})}}function lR(s){let e=xr();return Cf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function uR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(O.flags.useNewWSCLI.isEnabled()&&!e&&!t)return vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Go(),wh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Ho(),Eh));r.init(s)}}function pR(s,e){let{branch:t,autoDetect:r}=s;if(If(e,r),!e&&!r)throw new x(`branch ${t} does not exist, run aborted.`)}async function dR(s,e){let{id:t,type:r}=e,n=AT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=vi();n&&(s.sfdcCredential=await Np({projectId:t,branch:o}))}async function mR(s){if(!s.testDataFileName)return;let{testDataFileName:e}=s,t;try{t=(await Dp(`fileName=${e}&action=download&fileType=test-data&projectId=${s.project}`)).s3Url;let n=await(await fetch(t)).json();dt("test-data-file-used-in-cli",{projectId:s.project,testDataFileId:e,source:s.source}),s.testDataFileName=e,s.testDataString=n.testData}catch(r){let i=t?`, s3Url: ${t}`:"";throw new x(`Failed to read/open test data file error: ${r.message}${i}`)}}function fR(s,e){let{id:t,name:r,activePlan:i={}}=e,n=Boolean(i.isPoc),o=Boolean(i.isStartUp),a=jn(i);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<RT?RT:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(n),O.setIsStartUp(o),O.setPlanType(a),Lt.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:n,isStartUp:o,activePlan:i}}function gR(s,e){s.editorUrl=st||e}function hR(s,e){s.allGrids=e}function yR(s,e){s.authData=e}function bR(s,e){let{id:t,name:r,type:i,defaults:n}=e;O.setProjectId(t),O.setProjectType(i),s.projectData={projectId:t,type:i,name:r,defaults:n}}async function TR(s){var e;s.gridData=await vf(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function wR(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function vR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(dt("user-override-file",t),s.mockNetworkRules=await zb(s.overrideMappingFile))}async function SR(s){if(s.customCapabilitiesName){let e=await Wp(s.project,s.customCapabilitiesName);if(!e)throw new x(`"${s.customCapabilitiesName}" custom capabilities not found`);s.customCapabilities=e.capabilities}}async function ER(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:i,useChromeLauncher:n}=s;r||(s.source=i||n?"cli-local":"cli"),await cR(s),M("in runRunner before tunnel.connect"),await ac(s),M("in runRunner after tunnel.connect");let a=await new Wr(e).run(s);return M("before tunnel.disconnect"),await cc(s),await AR(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function RR(s){var e;Lt.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 kR(s,e,t){s==="redis"&&Ci.start(t,e),s==="mongo"&&wi.start(e)}async function OR(s,e,t){s==="redis"&&await Ci.end(t,e),s==="mongo"&&await wi.end(e)}async function _R(s){var h,g,y,v,b,T;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:i,disableSockets:n}=s,o=fR(e,{disableResults:n||Boolean((t==null?void 0:t.disableResults)&&(r||i===K.SELENIUM)),disableRemoteStep:n||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,companyByProjectId:c,projectById:l,branchName:d,allGrids:m,clientConfig:u}=await dn(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 w=m.sort((E,C)=>E.type.localeCompare(C.type));console.table(w.reduce((E,C)=>{class _{constructor(S,A){this.Type=S,this.Browsers=A}}let B=Object.entries(C.browsers||{"N/A":""}).map(V=>V.join(":")).join(", ");return E[C.name]=new _(C.type,B),E},{})),process.exit(0)}if(await o,M("after featureFlagsReady and socketConnected"),TR(s,u.editorUrl),bR(s,c),SR(s,l),IR(s,l),gR(s,d),wR(s,m),vR(s,a),await yR(s),await hR(s,l),await ER(s),await xR(s),pR(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[Ig(s)]),O.flags.clearRunnerFileCache.isEnabled())try{await ns(),gd.info("runner file cache cleared")}catch(w){gd.error("failed to clear runner file cache",{err:w})}(g=s.lightweightMode)!=null&&g.disableLabs||await Vi.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,((v=s.lightweightMode)==null?void 0:v.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`),kR(s.slotService,e,c.id),mR(e),await RR(s),PR(s);let f=Si();await Z.setOptions(s,f),(T=(b=s.testOptimization)==null?void 0:b.seaLights)!=null&&T.testStage&&s.testOptimization.seaLights.testStage!==cR&&us(a.uid,"cli-sealights_stage_changed",{testStage:s.testOptimization.seaLights.testStage,projectId:e})}var kT,AT,PT,cR,gd,uR,AR,_T=I(()=>{"use strict";kT=R(require("lodash"));F();fd();We();ls();gs();ps();Pl();ge();ut();er();W();Lt();oe();ae();X();Pp();Vo();Eu();de();Ri();Kp();Fi();AT=30*60*1e3,PT=1,cR="Testim Automation",gd=P("runner");uR={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};AR=CR});function DT(s){s.get("/",(e,t)=>{let r=hd();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Za()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());rd({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var LT=I(()=>{"use strict";sc();yd();Hp()});var bd,NT,Us,dc,MT=I(()=>{"use strict";bd=R(require("chalk"));xs();NT=require("express");W();X();Us=P("cli-router"),dc=(0,NT.Router)();dc.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:i,context:n,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!i||!n||!o||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d,nodePackageParams:i.nodePackageParams};try{let u=await Rs(t,r,i,n,o,a,c,l,d);u.success||(console.log(bd.default.red(u.result.resultValue)),Us.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){Us.error("failed to run cli code",{err:u,...m}),console.log(bd.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});dc.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:i,packageData:n,stepResultId:o,timeout:a}=s.body;if(!t||typeof n!="object"||!r||typeof i!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let c={stepId:t,testResultId:r,retryIndex:i,stepResultId:o,timeout:a,packageData:n};try{let l=await Is(t,r,i,n,o,a);Us.info("installed packages successfully",c),e.status(200).json({success:!0,data:l})}catch(l){if(l instanceof Pt){Us.error("failed to install node packages",{err:l,...c}),e.status(200).json({success:!1,code:"invalid-node-package",message:l.message});return}if(l instanceof ce){Us.error("timeout installing node package",{err:l,...c}),e.status(200).json({success:!1,code:"timeout"});return}Us.error("failed to install node packages",{err:l,...c}),e.status(500).json({success:!1,code:"internal-error"})}})});var FT=I(()=>{"use strict";MT()});var $T={};z($T,{orchestrateRoutes:()=>DR});function DR(s){let e=(0,BT.default)();e.disable("x-powered-by"),s(e),e.use(Td.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,jT.default)()),e.use(Td.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:Ve||kd?"*":["chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia"]};return e.use("*",(0,UT.default)(r)),DT(e),e.use("/cliJs",dc),e.use((i,n)=>{n.status(404).send("Endpoint Not Found")}),e}var UT,BT,Td,jT,WT=I(()=>{"use strict";UT=R(require("cors")),BT=R(require("express")),Td=R(require("body-parser")),jT=R(require("compression"));LT();FT();oe()});var GT={};z(GT,{init:()=>LR});async function LR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:i}=await Promise.resolve().then(()=>(WT(),$T));return new Promise((n,o)=>{let a=()=>{};t&&(hf(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let c=i(a),l=VT.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}`),NR()}})}async function NR(){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 VT,HT=I(()=>{"use strict";VT=R(require("http"));ut();X()});var QT={};z(QT,{getStartedWithStart:()=>hd,runAgentMode:()=>BR});async function BR(s){var r;let e;if(await Rr(s.playerLocation,s.canary),s.startTestimBrowser){await WR();try{e=await $R(s)}catch(i){throw(r=i==null?void 0:i.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'):i}}let t=await Promise.resolve().then(()=>(HT(),GT));return e!=null&&e.webdriverApi&&setTimeout(()=>{setTimeout(()=>(np(),ze(ab)))},6e3),t.init(s)}function hd(){return YT}function qT(s){try{return process.kill(s,0)}catch{return!1}}async function jR(s,e,t){let r=fr.join(Vt,`chrome-${fi}-process`),i=3e3,n=()=>{De.rmSync(r,{recursive:!0}),console.log(`
415
+ `)}function xR(s,e,t){s==="redis"&&xi.start(t,e),s==="mongo"&&Ti.start(e)}async function AR(s,e,t){s==="redis"&&await xi.end(t,e),s==="mongo"&&await Ti.end(e)}async function CR(s){var h,g,y,v,b,T;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:i,disableSockets:n}=s,o=uR(e,{disableResults:n||Boolean((t==null?void 0:t.disableResults)&&(r||i===K.SELENIUM)),disableRemoteStep:n||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,companyByProjectId:c,projectById:l,branchName:d,allGrids:m,clientConfig:u}=await pn(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 w=m.sort((E,A)=>E.type.localeCompare(A.type));console.table(w.reduce((E,A)=>{class _{constructor(S,C){this.Type=S,this.Browsers=C}}let B=Object.entries(A.browsers||{"N/A":""}).map(V=>V.join(":")).join(", ");return E[A.name]=new _(A.type,B),E},{})),process.exit(0)}if(await o,M("after featureFlagsReady and socketConnected"),gR(s,u.editorUrl),fR(s,c),bR(s,l),wR(s,l),pR(s,d),hR(s,m),yR(s,a),await mR(s),await dR(s,l),await TR(s),await SR(s),aR(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[vg(s)]),O.flags.clearRunnerFileCache.isEnabled())try{await rs(),md.info("runner file cache cleared")}catch(w){md.error("failed to clear runner file cache",{err:w})}(g=s.lightweightMode)!=null&&g.disableLabs||await Wi.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,((v=s.lightweightMode)==null?void 0:v.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`),xR(s.slotService,e,c.id),lR(e),await vR(s),RR(s);let f=vi();await Z.setOptions(s,f),(T=(b=s.testOptimization)==null?void 0:b.seaLights)!=null&&T.testStage&&s.testOptimization.seaLights.testStage!==iR&&as(a.uid,"cli-sealights_stage_changed",{testStage:s.testOptimization.seaLights.testStage,projectId:e})}var AT,RT,xT,iR,md,oR,IR,PT=I(()=>{"use strict";AT=R(require("lodash"));F();dd();We();os();ds();cs();Rl();ge();ut();er();W();Dt();ae();oe();Y();Ap();Wo();Tu();de();Ii();qp();Mi();RT=30*60*1e3,xT=1,iR="Testim Automation",md=P("runner");oR={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};IR=ER});function kT(s){s.get("/",(e,t)=>{let r=fd();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Xa()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());ed({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var OT=I(()=>{"use strict";ec();gd();Vp()});var hd,_T,Us,lc,LT=I(()=>{"use strict";hd=R(require("chalk"));Es();_T=require("express");W();Y();Us=P("cli-router"),lc=(0,_T.Router)();lc.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:i,context:n,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!i||!n||!o||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d,nodePackageParams:i.nodePackageParams};try{let u=await Ss(t,r,i,n,o,a,c,l,d);u.success||(console.log(hd.default.red(u.result.resultValue)),Us.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){Us.error("failed to run cli code",{err:u,...m}),console.log(hd.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});lc.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:i,packageData:n,stepResultId:o,timeout:a}=s.body;if(!t||typeof n!="object"||!r||typeof i!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let c={stepId:t,testResultId:r,retryIndex:i,stepResultId:o,timeout:a,packageData:n};try{let l=await vs(t,r,i,n,o,a);Us.info("installed packages successfully",c),e.status(200).json({success:!0,data:l})}catch(l){if(l instanceof Pt){Us.error("failed to install node packages",{err:l,...c}),e.status(200).json({success:!1,code:"invalid-node-package",message:l.message});return}if(l instanceof ce){Us.error("timeout installing node package",{err:l,...c}),e.status(200).json({success:!1,code:"timeout"});return}Us.error("failed to install node packages",{err:l,...c}),e.status(500).json({success:!1,code:"internal-error"})}})});var DT=I(()=>{"use strict";LT()});var UT={};z(UT,{orchestrateRoutes:()=>PR});function PR(s){let e=(0,MT.default)();e.disable("x-powered-by"),s(e),e.use(yd.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,FT.default)()),e.use(yd.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:Ve||Cd?"*":["chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia"]};return e.use("*",(0,NT.default)(r)),kT(e),e.use("/cliJs",lc),e.use((i,n)=>{n.status(404).send("Endpoint Not Found")}),e}var NT,MT,yd,FT,BT=I(()=>{"use strict";NT=R(require("cors")),MT=R(require("express")),yd=R(require("body-parser")),FT=R(require("compression"));OT();DT();ae()});var $T={};z($T,{init:()=>kR});async function kR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:i}=await Promise.resolve().then(()=>(BT(),UT));return new Promise((n,o)=>{let a=()=>{};t&&(mf(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let c=i(a),l=jT.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}`),OR()}})}async function OR(){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 jT,WT=I(()=>{"use strict";jT=R(require("http"));ut();Y()});var JT={};z(JT,{getStartedWithStart:()=>fd,runAgentMode:()=>NR});async function NR(s){var r;let e;if(await Ir(s.playerLocation,s.canary),s.startTestimBrowser){await UR();try{e=await FR(s)}catch(i){throw(r=i==null?void 0:i.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'):i}}let t=await Promise.resolve().then(()=>(WT(),$T));return e!=null&&e.webdriverApi&&setTimeout(()=>{setTimeout(()=>(tp(),ze(ib)))},6e3),t.init(s)}function fd(){return zT}function VT(s){try{return process.kill(s,0)}catch{return!1}}async function MR(s,e,t){let r=mr.join(Vt,`chrome-${mi}-process`),i=3e3,n=()=>{Le.rmSync(r,{recursive:!0}),console.log(`
417
417
 
418
- Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(De.readFileSync(r));if(qT(f.pid)){let h=()=>qT(f.pid)?setTimeout(h,i):n();return h(),{webdriverApi:f}}}let o=await ro();await ye(Bs)||await De.promises.mkdir(Bs,{recursive:!0});let c=[...XT(Bs,e,t,o).desiredCapabilities.chromeOptions.args,...fc.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",st||br).href,m=await fc.launch({chromeFlags:c,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Bs,chromePath:o,envVars:l}),u={port:m.port,pid:m.pid,cdpUrl:await Er(`localhost:${m.port}`)};return De.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",n),m.process.once("close",n),{webdriverApi:u}}async function $R(s){let e=`${Jt}/testim-full-master.zip`,t=fr.basename(e),r=fr.join(Vt,t),i=fr.join(Vt,`${t}__unzipped__`),n=!(s.ext||s.extensionPath);if(n&&await ye(r)){let f=await De.promises.stat(r);n=Date.now()-FR>f.mtimeMs}if(await De.promises.mkdir(Vt,{recursive:!0}),n){let f=(0,KT.default)("Downloading Testim Editor").start();await Ye(e,r);try{await ct(r,i)}catch{await De.promises.rm(r,{recursive:!0,force:!0}),await Ye(e,r);try{await ct(r,i)}catch{throw await De.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 De.promises.rm(i,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await De.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await jR(s,o,i);await ui({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=XT(Bs,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=(Wi(),ze(sh)),{SeleniumPerfStats:l}=(bs(),ze(yg)),d=new c;d.seleniumPerfStats=new l;let m=await d.initClient(a);YT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":st||br}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await Er(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function XT(s,e,t,r){let i=e?[e]:[],n=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];t&&n.push(`--load-extension=${t}`);try{let o=Mo();o.length&&o.forEach(a=>n.push(`--disable-features=${a}`))}catch{}return{logLevel:MR,desiredCapabilities:{chromeOptions:{args:n,extensions:i,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function WR(){if(await ye(mc))try{let{webSocketDebuggerUrl:s}=await VR();await GR(s),await De.promises.unlink(mc)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await De.promises.unlink(mc)}}async function VR(){let s=await De.promises.readFile(mc,{encoding:"utf8"}),[e,t]=s.split(`
419
- `).map(n=>n.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 i=await Er(`localhost:${r}`,500);if(!i.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:i}}async function GR(s,e=100){let t=await HR(s,e);return Qt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function HR(s,e=100){let t=Ha({timeout:e}),r=new JT.default(s,t),i=Qt(o=>{r.once("open",o)}).then(()=>{r.removeAllListeners()}),n=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return Promise.race([i,n]).then(()=>r)}var zT,KT,JT,De,fr,fc,MR,FR,Bs,UR,mc,YT,yd=I(()=>{"use strict";zT=R(require("ms")),KT=R(require("ora")),JT=R(require("ws")),De=R(require("node:fs")),fr=R(require("node:path")),fc=R(require("chrome-launcher"));oe();di();X();hl();F();Uo();qa();MR=Rn?"verbose":"silent",FR=(0,zT.default)("1h"),Bs=fr.join(Vt,"profile"),UR="DevToolsActivePort",mc=fr.join(Bs,UR);YT=!1});var QN=require("source-map-support/register");var Sn=R(require("os")),$s=R(require("url")),Ws=R(require("http")),yc=R(require("https")),hn=R(require("form-data")),yn=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 i;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let n of r)n==null||n.call(this,e);(i=this[`on${t}`])==null||i.call(this,e)}},bn=class extends yn{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),i=new Uint8Array(t);for(let n=0;n<t.byteLength;n++)r[n]=i[n];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),i=t.byteOffset,n=new Uint8Array(t.buffer);for(let o=0;o<t.byteLength;o++)r[o]=n[o+i];this._body=r}else if(typeof t=="object"&&t instanceof hn.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()}},js=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}},Tn=class extends Error{},wn=class extends Error{},vn=class extends Error{},hr=class extends Error{},Ae=class extends yn{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Ws.globalAgent;this.nodejsHttpsAgent=yc.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 (${Sn.type()} ${Sn.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 bn(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&&!$s.parse(r,!1,!0).protocol)throw new Tn("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,i){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new vn(`HTTP method ${t} is not allowed in XHR`);let n=this._parseUrl(r);i===void 0&&(i=!0),this._method=t,this._url=n,this._sync=!i,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 hr("XHR readyState must be OPENED");let i=t.toLowerCase();this._restrictedHeaders[i]||i.startsWith("sec-")||i.startsWith("proxy-")||(r=r.toString(),i in this._loweredHeaders?(t=this._loweredHeaders[i],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[i]=t,this._headers[t]=r))}send(t){if(this.readyState!==Ae.OPENED)throw new hr("XHR readyState must be OPENED");if(this._request)throw new hr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new wn(`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 i;let r=t.toLowerCase();return((i=this._responseHeaders)==null?void 0:i[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 hr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new js("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new wn("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,n=(this._url.protocol==="http:"?Ws:yc).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 hn.default&&t.pipe(n),this._request=n,this.timeout&&n.setTimeout(this.timeout,()=>this._onHttpTimeout(n)),n.on("response",o=>this._onHttpResponse(n,o)),n.on("error",()=>this._onHttpRequestError(n)),this.upload._startUpload(n),this._request===n&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof hn.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",n=>this._onHttpResponseData(r,n)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=Ws.STATUS_CODES[this.status],this._parseResponseHeaders(r);let i=this._responseHeaders["content-length"];i?(this._totalBytes=parseInt(i,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 js(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,i,n,o=this.nodejsBaseUrl===null?t:$s.resolve(this.nodejsBaseUrl,t),a=$s.parse(o,!1,!0);return a.hash=null,a.auth&&(n!=null||i!=null)&&(r=a.auth.indexOf(":"),r===-1?n||(n=a.auth):(n||(n=a.substring(0,r)),i||(i=a.substring(r+1)))),(n||i)&&(a.auth=`${n}:${i}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,i])=>{let n=r.toLowerCase();this._privateHeaders[n]||(this._mimeOverride!==null&&n==="content-type"&&(i=this._mimeOverride),this._responseHeaders[n]=i)}),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),i=new Uint8Array(r);for(let n=0;n<t.length;n++)i[n]=t[n];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=Tn,Ne.ProgressEvent=js,Ne.SecurityError=vn,Ne.XMLHttpRequest=Ae,Ne.InvalidStateError=hr,Ne.XMLHttpRequestUpload=bn,Ne.UNSENT=0,Ne.OPENED=1,Ne.HEADERS_RECEIVED=2,Ne.LOADING=3,Ne.DONE=4;Object.assign(global,{xhr2:Ne,XMLHttpRequest:Ne});var ZT=R(require("semver"));We();Kp();er();di();var wd=R(require("chalk")),ew=require("node:events");ae();ki();X();ae();uo();W();var Xb=R(require("os")),Jp=R(require("path")),Yp=R(require("chalk")),tc=require("fs");oe();function Qb(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let i=Xb.homedir();(0,tc.mkdirSync)(Jp.resolve(i,".testim_logs"),{recursive:!0});let n=Jp.resolve(i,".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(` ${n}`),Nd&&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(Yp.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(Yp.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,tc.writeFileSync)(n,`${s}
418
+ Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(Le.readFileSync(r));if(VT(f.pid)){let h=()=>VT(f.pid)?setTimeout(h,i):n();return h(),{webdriverApi:f}}}let o=await to();await ye(Bs)||await Le.promises.mkdir(Bs,{recursive:!0});let c=[...KT(Bs,e,t,o).desiredCapabilities.chromeOptions.args,...pc.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",st||yr).href,m=await pc.launch({chromeFlags:c,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Bs,chromePath:o,envVars:l}),u={port:m.port,pid:m.pid,cdpUrl:await Sr(`localhost:${m.port}`)};return Le.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",n),m.process.once("close",n),{webdriverApi:u}}async function FR(s){let e=`${Jt}/testim-full-master.zip`,t=mr.basename(e),r=mr.join(Vt,t),i=mr.join(Vt,`${t}__unzipped__`),n=!(s.ext||s.extensionPath);if(n&&await ye(r)){let f=await Le.promises.stat(r);n=Date.now()-LR>f.mtimeMs}if(await Le.promises.mkdir(Vt,{recursive:!0}),n){let f=(0,HT.default)("Downloading Testim Editor").start();await Xe(e,r);try{await ct(r,i)}catch{await Le.promises.rm(r,{recursive:!0,force:!0}),await Xe(e,r);try{await ct(r,i)}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(i,{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 MR(s,o,i);await li({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=KT(Bs,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=($i(),ze(eh)),{SeleniumPerfStats:l}=(gs(),ze(fg)),d=new c;d.seleniumPerfStats=new l;let m=await d.initClient(a);zT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":st||yr}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await Sr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function KT(s,e,t,r){let i=e?[e]:[],n=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];t&&n.push(`--load-extension=${t}`);try{let o=No();o.length&&o.forEach(a=>n.push(`--disable-features=${a}`))}catch{}return{logLevel:_R,desiredCapabilities:{chromeOptions:{args:n,extensions:i,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function UR(){if(await ye(uc))try{let{webSocketDebuggerUrl:s}=await BR();await jR(s),await Le.promises.unlink(uc)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Le.promises.unlink(uc)}}async function BR(){let s=await Le.promises.readFile(uc,{encoding:"utf8"}),[e,t]=s.split(`
419
+ `).map(n=>n.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 i=await Sr(`localhost:${r}`,500);if(!i.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:i}}async function jR(s,e=100){let t=await $R(s,e);return Qt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function $R(s,e=100){let t=Wa({timeout:e}),r=new qT.default(s,t),i=Qt(o=>{r.once("open",o)}).then(()=>{r.removeAllListeners()}),n=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return Promise.race([i,n]).then(()=>r)}var GT,HT,qT,Le,mr,pc,_R,LR,Bs,DR,uc,zT,gd=I(()=>{"use strict";GT=R(require("ms")),HT=R(require("ora")),qT=R(require("ws")),Le=R(require("node:fs")),mr=R(require("node:path")),pc=R(require("chrome-launcher"));ae();pi();Y();dl();F();Fo();Va();_R=In?"verbose":"silent",LR=(0,GT.default)("1h"),Bs=mr.join(Vt,"profile"),DR="DevToolsActivePort",uc=mr.join(Bs,DR);zT=!1});var zN=require("source-map-support/register");var vn=R(require("os")),$s=R(require("url")),Ws=R(require("http")),fc=R(require("https")),gn=R(require("form-data")),hn=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 i;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let n of r)n==null||n.call(this,e);(i=this[`on${t}`])==null||i.call(this,e)}},yn=class extends hn{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),i=new Uint8Array(t);for(let n=0;n<t.byteLength;n++)r[n]=i[n];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),i=t.byteOffset,n=new Uint8Array(t.buffer);for(let o=0;o<t.byteLength;o++)r[o]=n[o+i];this._body=r}else if(typeof t=="object"&&t instanceof gn.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()}},js=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}},bn=class extends Error{},Tn=class extends Error{},wn=class extends Error{},gr=class extends Error{},Ce=class extends hn{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Ws.globalAgent;this.nodejsHttpsAgent=fc.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 (${vn.type()} ${vn.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Ce.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new yn(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){Ce.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&&!$s.parse(r,!1,!0).protocol)throw new bn("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,i){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new wn(`HTTP method ${t} is not allowed in XHR`);let n=this._parseUrl(r);i===void 0&&(i=!0),this._method=t,this._url=n,this._sync=!i,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(Ce.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!==Ce.OPENED)throw new gr("XHR readyState must be OPENED");let i=t.toLowerCase();this._restrictedHeaders[i]||i.startsWith("sec-")||i.startsWith("proxy-")||(r=r.toString(),i in this._loweredHeaders?(t=this._loweredHeaders[i],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[i]=t,this._headers[t]=r))}send(t){if(this.readyState!==Ce.OPENED)throw new gr("XHR readyState must be OPENED");if(this._request)throw new gr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new Tn(`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 i;let r=t.toLowerCase();return((i=this._responseHeaders)==null?void 0:i[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
420
+ `):""}overrideMimeType(t){if([Ce.LOADING,Ce.DONE].includes(this.readyState))throw new gr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new js("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new Tn("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,n=(this._url.protocol==="http:"?Ws:fc).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 gn.default&&t.pipe(n),this._request=n,this.timeout&&n.setTimeout(this.timeout,()=>this._onHttpTimeout(n)),n.on("response",o=>this._onHttpResponse(n,o)),n.on("error",()=>this._onHttpRequestError(n)),this.upload._startUpload(n),this._request===n&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof gn.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",n=>this._onHttpResponseData(r,n)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=Ws.STATUS_CODES[this.status],this._parseResponseHeaders(r);let i=this._responseHeaders["content-length"];i?(this._totalBytes=parseInt(i,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Ce.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ce.LOADING&&this._setReadyState(Ce.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ce.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(Ce.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ce.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ce.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new js(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,i,n,o=this.nodejsBaseUrl===null?t:$s.resolve(this.nodejsBaseUrl,t),a=$s.parse(o,!1,!0);return a.hash=null,a.auth&&(n!=null||i!=null)&&(r=a.auth.indexOf(":"),r===-1?n||(n=a.auth):(n||(n=a.substring(0,r)),i||(i=a.substring(r+1)))),(n||i)&&(a.auth=`${n}:${i}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,i])=>{let n=r.toLowerCase();this._privateHeaders[n]||(this._mimeOverride!==null&&n==="content-type"&&(i=this._mimeOverride),this._responseHeaders[n]=i)}),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),i=new Uint8Array(r);for(let n=0;n<t.length;n++)i[n]=t[n];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=Ce;Ne.SyntaxError=bn,Ne.ProgressEvent=js,Ne.SecurityError=wn,Ne.XMLHttpRequest=Ce,Ne.InvalidStateError=gr,Ne.XMLHttpRequestUpload=yn,Ne.UNSENT=0,Ne.OPENED=1,Ne.HEADERS_RECEIVED=2,Ne.LOADING=3,Ne.DONE=4;Object.assign(global,{xhr2:Ne,XMLHttpRequest:Ne});var XT=R(require("semver"));We();qp();er();pi();var bd=R(require("chalk")),YT=require("node:events");oe();Pi();Y();oe();lo();W();var Kb=R(require("os")),zp=R(require("path")),Kp=R(require("chalk")),Qa=require("fs");ae();function Jb(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let i=Kb.homedir();(0,Qa.mkdirSync)(zp.resolve(i,".testim_logs"),{recursive:!0});let n=zp.resolve(i,".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(` ${n}`),Ld&&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(Kp.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(Kp.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Qa.writeFileSync)(n,`${s}
421
421
  ${s==null?void 0:s.stack}
422
422
 
423
- ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}ci();var UI=P("process-handler"),Zb=!1;function BI(s){return s instanceof Error?1:Zb?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:i,status:n})=>[t,n].includes(fe.SKIPPED)||[t,n].includes(fe.FAILED)&&i===Xe.EVALUATING?!1:r!==!0)?1:0)}function jI(){try{tr("chromedriver").stop()}catch{}}function eT(){Zb=!0}async function Xp(s){s!=null&&s.stack&&(ds?console.error(s,s.stack):Qb(s)),jI(),await UI.waitForFlush(),process.exit(BI(s))}ge();W();de();var qR=P("cli-entry");function zR(s){if(!ZT.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]),i=new Date("2026-04-30T00:00:00.000Z"),n=i<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(i);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&&n)throw new x(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(wd.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function KR(){console.log("Starting Testim.io CLI");let s=await Promise.resolve().then(()=>(F(),Q));M("Starting Testim.io CLI"),eg(Xp);try{zR(s.getEnginesVersion())}catch(e){console.log("Argument Error:",e.message),process.exit(1)}try{let e=await Promise.resolve().then(()=>(yT(),hT)),{program:t}=e;await O.fetch({proxy:t.proxy});let r=await e.process();if(M("in main, after options.process"),im(global.proxyUri),ew.EventEmitter.defaultMaxListeners="parallel"in r&&r.parallel>10?r.parallel*3:30,sm(r.project),jm("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(()=>(Oi(),ig));return await o()}if(s.isLoginMode(r))return;if(s.isCreatePrefetchedDataMode(r)){await ns(),await dn(r);let{preloadTests:o}=await Promise.resolve().then(()=>(Wo(),yh));await o(r),!r.playerRequirePath&&r.mode!==K.EXTENSION&&await Rr(r.playerLocation,r.canary);let a=await Um();a.success?console.log(`created prefetched data at ${zn()}`):console.error("failed to create prefetch data",a.error);return}let i=await Promise.resolve().then(()=>(_T(),OT));if(s.isTunnelOnlyMode(r)){await i.init(r);let{serveTunneling:o}=await Promise.resolve().then(()=>(fd(),md));await o(r);return}if(s.isAgentMode(r)){let{runAgentMode:o}=await Promise.resolve().then(()=>(yd(),QT));return o(r)}if(r.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(nu(),vg)),{port:a}=await o(r);r.localRCASaver=`http://localhost:${a}`}r.exitCodeIgnoreFailingTests&&eT(),M("right before testRunner.init/prepareRunner.prepare"),await i.init(r);let n=await Jb(r);return M("right after testRunner.init/prepareRunner.prepare"),await i.run(r,n)}catch(e){if(e instanceof zr)return;let t=s.getArgsOnRemoteRunFailure();return t&&await Vp({...t,error:e.message}).catch(()=>{}),e instanceof x?(console.log(wd.default.red("Argument Error:",e.message)),e):(console.log("Error:",e.message),qR.error("runner ended with unexpected error",{err:e}),e)}}KR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),Xp(s)});
423
+ ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}ai();var DI=P("process-handler"),Xb=!1;function NI(s){return s instanceof Error?1:Xb?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:i,status:n})=>[t,n].includes(fe.SKIPPED)||[t,n].includes(fe.FAILED)&&i===Ye.EVALUATING?!1:r!==!0)?1:0)}function MI(){try{tr("chromedriver").stop()}catch{}}function Yb(){Xb=!0}async function Jp(s){s!=null&&s.stack&&(ls?console.error(s,s.stack):Jb(s)),MI(),await DI.waitForFlush(),process.exit(NI(s))}ge();W();de();var WR=P("cli-entry");function VR(s){if(!XT.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]),i=new Date("2026-04-30T00:00:00.000Z"),n=i<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(i);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&&n)throw new x(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(bd.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function GR(){console.log("Starting Testim.io CLI");let s=await Promise.resolve().then(()=>(F(),Q));M("Starting Testim.io CLI"),Yf(Jp);try{VR(s.getEnginesVersion())}catch(e){console.log("Argument Error:",e.message),process.exit(1)}try{let e=await Promise.resolve().then(()=>(fT(),mT)),{program:t}=e;await O.fetch({proxy:t.proxy});let r=await e.process();if(M("in main, after options.process"),tm(global.proxyUri),YT.EventEmitter.defaultMaxListeners="parallel"in r&&r.parallel>10?r.parallel*3:30,em(r.project),Fm("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(()=>(ki(),tg));return await o()}if(s.isLoginMode(r))return;if(s.isCreatePrefetchedDataMode(r)){await rs(),await pn(r);let{preloadTests:o}=await Promise.resolve().then(()=>($o(),fh));await o(r),!r.playerRequirePath&&r.mode!==K.EXTENSION&&await Ir(r.playerLocation,r.canary);let a=await Nm();a.success?console.log(`created prefetched data at ${qn()}`):console.error("failed to create prefetch data",a.error);return}let i=await Promise.resolve().then(()=>(PT(),CT));if(s.isTunnelOnlyMode(r)){await i.init(r);let{serveTunneling:o}=await Promise.resolve().then(()=>(dd(),pd));await o(r);return}if(s.isAgentMode(r)){let{runAgentMode:o}=await Promise.resolve().then(()=>(gd(),JT));return o(r)}if(r.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(tu(),bg)),{port:a}=await o(r);r.localRCASaver=`http://localhost:${a}`}r.exitCodeIgnoreFailingTests&&Yb(),M("right before testRunner.init/prepareRunner.prepare"),await i.init(r);let n=await qb(r);return M("right after testRunner.init/prepareRunner.prepare"),await i.run(r,n)}catch(e){if(e instanceof Gr)return;let t=s.getArgsOnRemoteRunFailure();return t&&await $p({...t,error:e.message}).catch(()=>{}),e instanceof x?(console.log(bd.default.red("Argument Error:",e.message)),e):(console.log("Error:",e.message),WR.error("runner ended with unexpected error",{err:e}),e)}}GR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),Jp(s)});
424
424
  //# sourceMappingURL=cli.js.map