@testim/testim-cli 4.165.0 → 4.169.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -1,55 +1,55 @@
1
1
  #! /usr/bin/env node
2
- "use strict";var XT=Object.create;var ui=Object.defineProperty;var YT=Object.getOwnPropertyDescriptor;var QT=Object.getOwnPropertyNames;var ZT=Object.getPrototypeOf,ew=Object.prototype.hasOwnProperty;var E=(s,e)=>()=>(s&&(e=s(s=0)),e);var z=(s,e)=>{for(var t in e)ui(s,t,{get:e[t],enumerable:!0})},bd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of QT(e))!ew.call(s,n)&&n!==t&&ui(s,n,{get:()=>e[n],enumerable:!(r=YT(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?XT(ZT(s)):{},bd(e||!s||!s.__esModule?ui(t,"default",{value:s,enumerable:!0}):t,s)),qe=s=>bd(ui({},"__esModule",{value:!0}),s);var je={};z(je,{log:()=>F,measure:()=>rw});function F(...s){if(!wd)return;let e=Date.now();console.log(`${e-tw} ${e-Td} `,...s),Td=e}function rw(s,e){if(!wd)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var wd,tw,Td,$e=E(()=>{"use strict";wd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,tw=Date.now(),Td=Date.now()});var Jt,Hr=E(()=>{"use strict";Jt="element-6066-11e4-a52e-4f735466cecf"});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function ze(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function mc(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function De(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 fc=E(()=>{"use strict"});var hc,vd,Sd,bi=E(()=>{hc={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"},vd={"@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"},Sd={node:">= 18.0.0"}});var fr,gr,Ed,xt,iw,mt,Id,Rd,Ti,tt,xd,he,Ad,Cd,wi,We,yc,Pd,vi,kd,Od,zR,KR,_d,Ld,Dd,Nd,bc,Tc,wc,vc,Md,Vs,Fd,Sc,Gs,oe=E(()=>{"use strict";fr=process.env.SERVICES_HOST||"",gr="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:fr,fr=process.env.SERVICES_HOST);Ed=process.env.TESTIM_REGION||"us-west-2",xt=process.env.RUNNER_ENVIRONMENT||"production",iw={production:"",staging:".staging",development:".dev"},mt=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${iw[xt]||""}.testim.io`,Id=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Rd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),Ti=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),tt=process.env.EDITOR_URL,xd=process.env.WEBSOCKET_HOST||`${fr}/ws`,he=()=>fr,Ad=parseInt(process.env.LOGGER_CONSOLE||"0",10),Cd=parseInt(process.env.LOGGER_DEBUG||"0",10),wi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),We=parseInt(process.env.IS_ON_PREM||"0",10),yc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Pd=parseInt(process.env.DEBUG_MODE||"0",10),vi=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,kd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",Od=process.env.CORALOGIX_PRIVATE_KEY||"",zR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),KR=process.env.APPIUM_VERSION||"1.10.1",_d=process.env.GATEWAY_URL,Ld=()=>process.env.EXTENSION_SERVICES_HOST||fr,Dd=5*60*1e3,Nd=40,bc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",Tc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",wc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",vc=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Md=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Vs=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Fd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,Sc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung",Gs=s=>{fr=s,process.env.SERVICES_HOST=s,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:fr}});var Ud,Si,Bd=E(()=>{"use strict";Ud=I(require("superagent"));oe();Si=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=Od,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=Ud.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 $d={};z($d,{CoralogixTransport:()=>Ec});var jd,ow,aw,Ec,Wd=E(()=>{"use strict";jd=I(require("winston-transport"));Bd();ow={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},aw=["err","error","reason","e"],Ec=class extends jd.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new Si({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...c}=t,l={...a,...c},m={severity:ow[i],text:o,category:n||this.category};l.className&&(m.className=l.className),l.methodName&&(m.methodName=l.methodName),l.threadId&&(m.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let d=!1;a instanceof Error&&(d=!0,l.msg=a.message+a.stack,o&&(l.msg=`${o}
3
- ${l.msg}`));for(let u of aw)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&&!d&&(l.msg=o),m.text=JSON.stringify(l)),this.logger.addLog(m),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function uw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!We){let{CoralogixTransport:r}=(Wd(),qe($d)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(Ad){let r={depth:5,colors:!0};s.push(new ft.transports.Console({format:ft.format.combine(ft.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),ft.format.timestamp({format:"HH:mm:ss:SSS"}),ft.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ii.inspect(n.meta,r)}`))}))}return[s,e,t]}function Jd(s){Ic=s}function Xd(s){Kd=s}function Yd(s){We||!s||mw(s)}function Gd(s){return{projectId:Kd,time:new Date().toISOString(),region:Ut.getRegion(),...Ic&&!s&&{executionId:Ic}}}function P(s){return new Ut(hw.child({category:s}))}var Hd,ft,Ii,Ei,qd,cw,lw,Vd,zd,pw,dw,mw,fw,gw,hw,Ic,Kd,Ut,$=E(()=>{"use strict";Hd=I(require("node:os")),ft=I(require("winston"));oe();Ii=I(require("node:util")),Ei=I(require("chalk")),qd=I(require("dayjs"));B();cw=Hd.hostname(),lw=rt();Vd={depth:5,colors:!0},zd=(s,e,t)=>{let r=`[${(0,qd.default)().format("HH:mm:ss:SSS")}]`,n=Ii.inspect(e,Vd),i=Ii.inspect(t,Vd);return`${Ei.default.white(r)} ${Ei.default.reset()}SessionPlayer-${Ei.default.red(s)} ${n} ${i}`},[pw,dw,mw]=uw(),fw=Cd?"debug":"info",gw={release:Boolean(!1),branch:"test"},hw=ft.createLogger({levels:ft.config.syslog.levels,level:fw,transports:pw,defaultMeta:{name:"runner",hostname:cw,nodeVersion:process.version,runnerVersion:lw,...gw}}),Ic=null,Kd=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:n}=r;try{this._logger.log(e,{meta:r,message:t,...Gd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Gd(n)})}catch{}}}waitForFlush(){return dw()}}});var Ci,qr,C,Xt,hr,At,Ri,zr,ce,Hs,st,Yt,Ct,xi,Kr,Ai,qs,Y=E(()=>{"use strict";Ci=require("p-retry"),qr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Xt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},hr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},At=class extends Ci.AbortError{},Ri=class extends Ci.AbortError{},zr=class extends Ci.AbortError{},ce=class extends Error{},Hs=class extends Error{},st=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Yt=class extends st{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Ct=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},xi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Kr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Ai=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},qs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Rc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function pe(s){return(0,em.setTimeout)(s)}function xc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function le(s,e,t="Timeout Error"){Ti&&!Qd&&(Qd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ce(t);return e=Ti?Number(Ti)||6e5:e,Promise.race([s,pe(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Zd||=(await import("p-limit")).default;let r=Zd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Qt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var em,Qd,Zd,Ac=E(()=>{"use strict";em=require("timers/promises");Y();oe();Qd=!1});var Ks,tm,bw,zs,rm,Tw,ww,sm,nm=E(()=>{"use strict";Ks=I(require("lodash"));oe();tm=require("dns");$();Ac();bw=P("http-request-counters"),zs=!1,rm=async()=>{if(We)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>tm.promises.lookup(t)));return e||(zs=!0),e}catch{return bw.error("network connectivity test failed"),zs=!0,!1}},Tw=Ks.throttle(rm,10*1e3),ww=60*1e3*15,sm=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},ww)}function t(n,i=n.name){return async function(...o){e(s.call,i);try{let a=await n.call(null,...o);return e(s.success,i),a}catch(a){throw e(s.fail,i),zs||Tw(),a}}}async function r(){if(zs||!await rm())return!1;let n=Ks.sum([...s.fail.values()]),i=Ks.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>zs,t}});var Ke={};z(Ke,{deleteReq:()=>Js,didNetworkConnectivityTestFail:()=>Dc,download:()=>_c,get:()=>Te,getFullRes:()=>Rw,getText:()=>Ys,head:()=>xw,isNetworkHealthy:()=>Lc,post:()=>Ve,postForm:()=>Xs,postText:()=>kc,put:()=>Oc});function Sw(){return global.caFileContent}function Ew(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function Iw(){return!gt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(gt.default),global.proxyUri}function yr(s,e=!1){let t=Sw();t&&s.ca(t);let r=!e&&Iw();r&&s.proxy(r)}async function im(s,e,t={},r=Jr,n=0){let i=gt.default.post(s).send(e).timeout(r).set(t);yr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Pc(s,e,t={},r=Jr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=gt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),yr(o,i),await o}var gt,Cc,nt,Jr,vw,Bt,Js,Ve,Xs,Ys,kc,Te,Rw,xw,Oc,_c,Lc,Dc,Ge=E(()=>{"use strict";gt=I(require("superagent"));$();nm();Cc=P("http-request"),nt=sm(),Jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,vw=6e4;Bt=(s,e,t)=>{let r=e.response;e.response instanceof gt.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw Cc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Js=nt(async(s,e={},t={},r=Jr)=>{try{let n=gt.default.delete(s).send(e).timeout(r).set(t);yr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Bt("failed to delete request",n,{url:s})}}),Ve=nt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await im(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Bt("failed to post request",i,{url:s})}});Xs=nt(async(s,e,t,r={},n=Jr)=>{let i=gt.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),yr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Bt("failed to post request",o,{url:s})}});Ys=nt(async(s,e,t)=>{try{return(await Pc(s,e,t)).text}catch(r){return Bt("failed to getText request",r,{url:s,query:e})}}),kc=nt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await im(s,e,t,r,n)).text}catch(i){return Bt("failed to post request",i,{url:s})}}),Te=nt(async(s,e,t,r,n)=>{try{return(await Pc(s,e,t,r,n)).body}catch(i){return Bt("failed to get request",i,{url:s,query:e})}}),Rw=nt((s,e,t,r)=>Pc(s,e,t,r)),xw=nt(async s=>{let e=gt.default.head(s).timeout(Jr);yr(e);try{return await e}catch(t){return Bt("failed to head request",t,{url:s})}}),Oc=nt(async(s,e,t={},r=Jr)=>{let n=gt.default.put(s).send(e).timeout(r).set(t);yr(n);try{return(await n).body}catch(i){return Bt("failed to put request",i,{url:s})}}),_c=nt(async s=>{Cc.info("start to download",{url:s});let e=gt.default.get(s).set("User-Agent","Testim.io").timeout(vw).buffer(!0).parse(Ew);yr(e);try{let t=await e;return Cc.info("finished to download",{url:s}),t}catch(t){return Bt("failed to download",t,{url:s})}}),Lc=nt.isNetworkHealthy,Dc=nt.didNetworkConnectivityTestFail});function ht(){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 Pi(s,e){return De(s)?e||jt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||jt.basename(s)}function rt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Fc(){try{return Sd.node}catch{return""}}async function cm(s,e,t=!0){let r=await it.promises.readdir(s,{withFileTypes:!0});await it.promises.mkdir(e,{recursive:t});for(let n of r){let i=jt.join(s,n.name),o=jt.join(e,n.name);n.isDirectory()?await cm(i,o):await it.promises.copyFile(i,o)}}async function ye(s){try{return await it.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var jt,om,am,it,Aw,$t,Je,ki,Nc,ot,Mc,lm=E(()=>{"use strict";jt=I(require("node:path"));fc();bi();om=I(require("unzip-stream")),am=I(require("p-retry")),it=require("node:fs"),Aw=3;$t=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Ke));return(0,am.default)(()=>e.download(s),{retries:Aw,factor:1})},Je=async(s,e)=>{let t=await $t(s);return it.promises.writeFile(e,t.body)};ki=async(s,e)=>{let t=Pi(s,e);return De(s)?Je(s,t):it.promises.copyFile(s,t)},Nc=async s=>De(s)?$t(s):it.promises.readFile(s),ot=async(s,e)=>(0,it.createReadStream)(s).pipe(om.Extract({path:e})),Mc=s=>(0,it.statSync)(s).size/1e6});var Wt={};z(Wt,{APPIUM_SESSION_MESSAGE:()=>Wc,CLI_MODE:()=>K,MOBILE_APP_SOURCE:()=>Oi,MOBILE_RUN_SKIP_REASON:()=>$c,REGION_CONFIG:()=>Yr,X_HEADER_RUNNER_ID:()=>Vc,gridMessages:()=>yt,gridTypes:()=>_,mobileWeb:()=>Bc,runnerStatus:()=>Uc,runnerTestStatus:()=>fe,socketEventTypes:()=>Pt,stepResult:()=>Xr,test:()=>jc,testRunStatus:()=>Qs,testStatus:()=>Xe,timeoutMessages:()=>Ae});var Ae,Qs,Uc,fe,Xe,yt,Bc,jc,Pt,K,_,Xr,Oi,$c,Wc,Vc,Yr,ae=E(()=>{"use strict";Ae={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"},Uc={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"},yt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Bc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},jc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Pt={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"},_={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},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"},Oi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},$c={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Wc={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"},Vc="X-Testim-Runner-ID",Yr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"}});function Zs(s,e){var t,r,n,i,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(n=s.browser)==null?void 0:n.toLowerCase()]:(i=s.testConfigNames)!=null&&i.length||(o=s.testConfigIds)!=null&&o.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(c=>{var l;return(l=c.runConfig)==null?void 0:l.browserValue}))]:[(a=s.browser)==null?void 0:a.toLowerCase()]}function Cw(){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 en,um,Ye,Pw,kw,Ow,_w,Lw,Gc,Hc,pm=E(()=>{"use strict";ae();en=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},um=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Xe.QUARANTINE&&!um(e)&&!e.runQuarantinedTests;Pw=s=>Boolean(s.loginMode),kw=s=>Boolean(s.tunnelOnlyMode),Ow=s=>Boolean(s.createPrefechedData),_w=s=>Boolean(s.installLazyDepsMode),Lw=s=>Boolean(s.agentMode),Gc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Hc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Li(s=0){return _i.default.duration(s).format("HH:mm:ss.SSS")}function qc(s=0){return _i.default.duration(s).asSeconds()}var _i,dm,zc,mm=E(()=>{"use strict";_i=I(require("dayjs")),dm=I(require("dayjs/plugin/duration"));_i.default.extend(dm.default);zc=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 tn,Qr,Zt,fm,Zr,gm=E(()=>{"use strict";ae();tn=s=>!(!s||"fileName"in s),Qr=(s,e)=>{if(e===_.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"},fm=s=>s===_.TESTIM_TVC,Zr=(s,e)=>fm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Kc(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 hm=E(()=>{"use strict"});var X={};z(X,{OSS:()=>es,TESTIM_BROWSER_DIR:()=>Vt,buildBasicHeader:()=>mc,calcPercentile:()=>Mi,copyDir:()=>cm,delay:()=>pe,doesPathExist:()=>ye,download:()=>$t,downloadAndSave:()=>Je,extractElementId:()=>Ne,formatTimeoutDuration:()=>zc,getArgsOnRemoteRunFailure:()=>Cw,getBrowserInfo:()=>Nw,getCdpAddressForHost:()=>wr,getCliLocation:()=>ht,getDuration:()=>Li,getDurationSec:()=>qc,getEnginesVersion:()=>Fc,getEnvironmentGitBranch:()=>Tr,getLinksFromUnescapeHTML:()=>nn,getLocalFileSizeInMB:()=>Mc,getMemorySnapshot:()=>Kc,getPlanType:()=>Ni,getRunConfigByBrowserName:()=>rn,getRunnerVersion:()=>rt,getSource:()=>ki,getSourceAsBuffer:()=>Nc,getSourcePath:()=>Pi,getTestUrl:()=>ze,getUniqBrowsers:()=>Zs,groupTestsByRetries:()=>Xc,guid:()=>re,hasTestPlanFlag:()=>en,isAgentMode:()=>Lw,isAppFromDevice:()=>tn,isAppFromDeviceDisabled:()=>Zr,isCreatePrefetchedDataMode:()=>Ow,isInstallLazyDepsMode:()=>_w,isLoginMode:()=>Pw,isMobileProject:()=>Zt,isPromise:()=>Rc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>um,isTestimVirtualGrid:()=>fm,isTunnelOnlyMode:()=>kw,isURL:()=>De,promiseAbort:()=>xc,promiseFromCallback:()=>Qt,promiseMap:()=>se,promiseTimeout:()=>le,removePropertyFromObject:()=>Di,replaceArgsWithNoDashes:()=>Gc,sanitizeNumberValue:()=>br,shouldBlockVirtualIosBuild:()=>Qr,spreadObjectToArgs:()=>Hc,unescapeHTML:()=>sn,unzipFile:()=>ot});function br(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function Nw(s){return s=s.toLowerCase(),Jc.find(e=>e.browserValue===s)}function rn(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Jc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Jc[0],n=es.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=es.find(i=>i.sl.platform===e.platform):e.platformName&&(n=es.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=es.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=es.find(i=>i.bs.platform===t.platform))),ts.merge(r,n)}function Tr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Di(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Di(s[r],e,t))}function Ne(s){return s.ELEMENT||s[Jt]}function Ni(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Xc(s=[]){return ts.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=ts.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function sn(s){return vm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function nn(s){return[...vm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function wr(s,e){let t=await Promise.resolve().then(()=>(Ge(),Ke));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 bm,ts,Tm,wm,Dw,Vt,ym,es,Jc,Mi,vm,B=E(()=>{"use strict";bm=I(require("os")),ts=I(require("lodash")),Tm=I(require("path")),wm=require("linkedom");Hr();lm();pm();mm();fc();Ac();gm();hm();Dw=bm.homedir(),Vt=Tm.join(Dw,".testim-browser-profile"),ym="133",es=[{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"}}],Jc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:ym},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:ym},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"}];Mi=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};vm=new wm.DOMParser});var Yc={};z(Yc,{$schema:()=>Mw,default:()=>$w,definitions:()=>Fw,properties:()=>jw,required:()=>Bw,type:()=>Uw});var Mw,Fw,Uw,Bw,jw,$w,Sm=E(()=>{Mw="http://json-schema.org/draft-07/schema#",Fw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},Uw="object",Bw=["entries"],jw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},$w={$schema:Mw,definitions:Fw,type:Uw,required:Bw,properties:jw}});async function Pm(){try{return await le(Fi.promises.readFile($i()).then(async s=>{let e=await Cm;return Gw(e,s)}),3e4)}catch{return{}}}function Gw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=ss.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function kt(s,e,t=Ww,r=void 0){return async()=>{if(!Rm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Zc(e);if(i)return on.debug("cache hit:",{fnName:e}),i;if(on.debug("cache miss:",{fnName:e}),!xm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Hw(e,o,t),o}}async function Zc(s){let t=(await Wi)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Hw(s,e,t){if(Qc)throw on.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 Wi;r[s]={value:e,expiry:Date.now()+t},Am=new Promise(n=>{ji=n}),Vw(r)}catch{on.error("failed updating cache")}}async function ns(){let s=await Wi;Object.keys(s).forEach(e=>{delete s[e]})}function km(s){Rm=s}function qw(s=!0){xm=s}async function Om(){try{return Qc=!0,await Am}finally{Qc=!1}}function _m(s){Bi=s,Wi=Pm()}var Fi,Ui,ss,Em,on,Bi,Im,ji,Rm,xm,Qc,Am,Cm,Ww,$i,Wi,Vw,Lm,Dm,Ix,Nm,er=E(()=>{"use strict";Fi=I(require("fs")),Ui=I(require("path")),ss=I(require("crypto"));B();Em=require("lodash");$();on=P("local cache"),Bi=Ui.resolve(ht(),"testim-cache"),Rm=!0,xm=!0,Qc=!1,Am=new Promise(s=>{ji=s}),Cm=new Promise(s=>{Im=s}),Ww=1e3*60*60*3,$i=()=>Ui.resolve(Ui.resolve(Bi,"testim.cache"));Wi=Pm(),Vw=(0,Em.debounce)(async s=>{let e;try{let t=await Cm,r=ss.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=ss.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Bi)||await Fi.promises.mkdir(Bi,{recursive:!0}),await Fi.promises.writeFile($i(),a)}catch(t){on.error("failed saving cache",{err:t}),e=t}ji(e?{success:!1,error:e}:{success:!0})},200);Lm=Im,Dm=km.bind(void 0,!1),Ix=km.bind(void 0,!0),Nm=()=>qw(!1)});function Vi(){return{cliLocation:ht(),userInfo:is.userInfo(),platform:is.platform(),release:is.release()}}var is,el=E(()=>{"use strict";is=I(require("node:os"));B()});function zw(s){try{return Gi.resolve(Gi.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 Gi,an=E(()=>{"use strict";Gi=I(require("path"))});function Kw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Jw(s){return/The "to" argument must be of type string./.exec(s)}function Bm(s,e,t){let r=Kw(s),n=Jw(s);return r||n?(Um.info("Failed to install package due to insufficient write access",{...Vi(),package:t,path:r}),console.error(`
2
+ "use strict";var YT=Object.create;var pi=Object.defineProperty;var QT=Object.getOwnPropertyDescriptor;var ZT=Object.getOwnPropertyNames;var ew=Object.getPrototypeOf,tw=Object.prototype.hasOwnProperty;var S=(s,e)=>()=>(s&&(e=s(s=0)),e);var z=(s,e)=>{for(var t in e)pi(s,t,{get:e[t],enumerable:!0})},wd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ZT(e))!tw.call(s,n)&&n!==t&&pi(s,n,{get:()=>e[n],enumerable:!(r=QT(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?YT(ew(s)):{},wd(e||!s||!s.__esModule?pi(t,"default",{value:s,enumerable:!0}):t,s)),qe=s=>wd(pi({},"__esModule",{value:!0}),s);var je={};z(je,{log:()=>F,measure:()=>sw});function F(...s){if(!Sd)return;let e=Date.now();console.log(`${e-rw} ${e-vd} `,...s),vd=e}function sw(s,e){if(!Sd)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var Sd,rw,vd,$e=S(()=>{"use strict";Sd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,rw=Date.now(),vd=Date.now()});var Jt,Hr=S(()=>{"use strict";Jt="element-6066-11e4-a52e-4f735466cecf"});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function ze(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function hc(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function De(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 yc=S(()=>{"use strict"});var Tc,Ed,Id,Ti=S(()=>{Tc={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"},Ed={"@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"},Id={node:">= 18.0.0"}});var gr,hr,Rd,At,ow,ft,xd,Ad,wi,tt,Cd,he,Pd,kd,vi,We,wc,Od,Si,_d,Ld,JR,XR,Dd,Nd,Md,Fd,vc,Sc,Ec,Ic,Ud,Vs,Bd,Rc,Gs,oe=S(()=>{"use strict";gr=process.env.SERVICES_HOST||"",hr="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:gr,gr=process.env.SERVICES_HOST);Rd=process.env.TESTIM_REGION||"us-west-2",At=process.env.RUNNER_ENVIRONMENT||"production",ow={production:"",staging:".staging",development:".dev"},ft=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${ow[At]||""}.testim.io`,xd=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Ad=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),wi=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),tt=process.env.EDITOR_URL,Cd=process.env.WEBSOCKET_HOST||`${gr}/ws`,he=()=>gr,Pd=parseInt(process.env.LOGGER_CONSOLE||"0",10),kd=parseInt(process.env.LOGGER_DEBUG||"0",10),vi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),We=parseInt(process.env.IS_ON_PREM||"0",10),wc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Od=parseInt(process.env.DEBUG_MODE||"0",10),Si=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,_d=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",Ld=process.env.CORALOGIX_PRIVATE_KEY||"",JR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),XR=process.env.APPIUM_VERSION||"1.10.1",Dd=process.env.GATEWAY_URL,Nd=()=>process.env.EXTENSION_SERVICES_HOST||gr,Md=5*60*1e3,Fd=40,vc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",Sc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",Ec=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",Ic=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Ud=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Vs=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Bd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,Rc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung",Gs=s=>{gr=s,process.env.SERVICES_HOST=s,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:gr}});var jd,Ei,$d=S(()=>{"use strict";jd=I(require("superagent"));oe();Ei=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=Ld,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=jd.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 Vd={};z(Vd,{CoralogixTransport:()=>xc});var Wd,aw,cw,xc,Gd=S(()=>{"use strict";Wd=I(require("winston-transport"));$d();aw={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},cw=["err","error","reason","e"],xc=class extends Wd.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new Ei({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...c}=t,l={...a,...c},m={severity:aw[i],text:o,category:n||this.category};l.className&&(m.className=l.className),l.methodName&&(m.methodName=l.methodName),l.threadId&&(m.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let d=!1;a instanceof Error&&(d=!0,l.msg=a.message+a.stack,o&&(l.msg=`${o}
3
+ ${l.msg}`));for(let u of cw)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&&!d&&(l.msg=o),m.text=JSON.stringify(l)),this.logger.addLog(m),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function pw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!We){let{CoralogixTransport:r}=(Gd(),qe(Vd)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(Pd){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(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ri.inspect(n.meta,r)}`))}))}return[s,e,t]}function Yd(s){Ac=s}function Qd(s){Xd=s}function Zd(s){We||!s||fw(s)}function qd(s){return{projectId:Xd,time:new Date().toISOString(),region:Bt.getRegion(),...Ac&&!s&&{executionId:Ac}}}function P(s){return new Bt(yw.child({category:s}))}var zd,gt,Ri,Ii,Kd,lw,uw,Hd,Jd,dw,mw,fw,gw,hw,yw,Ac,Xd,Bt,W=S(()=>{"use strict";zd=I(require("node:os")),gt=I(require("winston"));oe();Ri=I(require("node:util")),Ii=I(require("chalk")),Kd=I(require("dayjs"));B();lw=zd.hostname(),uw=rt();Hd={depth:5,colors:!0},Jd=(s,e,t)=>{let r=`[${(0,Kd.default)().format("HH:mm:ss:SSS")}]`,n=Ri.inspect(e,Hd),i=Ri.inspect(t,Hd);return`${Ii.default.white(r)} ${Ii.default.reset()}SessionPlayer-${Ii.default.red(s)} ${n} ${i}`},[dw,mw,fw]=pw(),gw=kd?"debug":"info",hw={release:Boolean(!1),branch:"test"},yw=gt.createLogger({levels:gt.config.syslog.levels,level:gw,transports:dw,defaultMeta:{name:"runner",hostname:lw,nodeVersion:process.version,runnerVersion:uw,...hw}}),Ac=null,Xd=null;Bt=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){Bt.region=e}static getRegion(){return Bt.region}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...qd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...qd(n)})}catch{}}}waitForFlush(){return mw()}}});var Pi,qr,C,Xt,yr,Ct,xi,zr,ce,Hs,st,Yt,Pt,Ai,Kr,Ci,qs,Y=S(()=>{"use strict";Pi=require("p-retry"),qr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Xt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},yr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},Ct=class extends Pi.AbortError{},xi=class extends Pi.AbortError{},zr=class extends Pi.AbortError{},ce=class extends Error{},Hs=class extends Error{},st=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Yt=class extends st{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Pt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Ai=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Kr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Ci=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},qs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Cc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function pe(s){return(0,rm.setTimeout)(s)}function Pc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function le(s,e,t="Timeout Error"){wi&&!em&&(em=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ce(t);return e=wi?Number(wi)||6e5:e,Promise.race([s,pe(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){tm||=(await import("p-limit")).default;let r=tm(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Qt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var rm,em,tm,kc=S(()=>{"use strict";rm=require("timers/promises");Y();oe();em=!1});var Ks,sm,Tw,zs,nm,ww,vw,im,om=S(()=>{"use strict";Ks=I(require("lodash"));oe();sm=require("dns");W();kc();Tw=P("http-request-counters"),zs=!1,nm=async()=>{if(We)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>sm.promises.lookup(t)));return e||(zs=!0),e}catch{return Tw.error("network connectivity test failed"),zs=!0,!1}},ww=Ks.throttle(nm,10*1e3),vw=60*1e3*15,im=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},vw)}function t(n,i=n.name){return async function(...o){e(s.call,i);try{let a=await n.call(null,...o);return e(s.success,i),a}catch(a){throw e(s.fail,i),zs||ww(),a}}}async function r(){if(zs||!await nm())return!1;let n=Ks.sum([...s.fail.values()]),i=Ks.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>zs,t}});var Ke={};z(Ke,{deleteReq:()=>Js,didNetworkConnectivityTestFail:()=>Fc,download:()=>Nc,get:()=>Te,getFullRes:()=>xw,getText:()=>Ys,head:()=>Aw,isNetworkHealthy:()=>Mc,post:()=>Ve,postForm:()=>Xs,postText:()=>Lc,put:()=>Dc});function Ew(){return global.caFileContent}function Iw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function Rw(){return!ht.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(ht.default),global.proxyUri}function br(s,e=!1){let t=Ew();t&&s.ca(t);let r=!e&&Rw();r&&s.proxy(r)}async function am(s,e,t={},r=Jr,n=0){let i=ht.default.post(s).send(e).timeout(r).set(t);br(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function _c(s,e,t={},r=Jr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=ht.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),br(o,i),await o}var ht,Oc,nt,Jr,Sw,jt,Js,Ve,Xs,Ys,Lc,Te,xw,Aw,Dc,Nc,Mc,Fc,Ge=S(()=>{"use strict";ht=I(require("superagent"));W();om();Oc=P("http-request"),nt=im(),Jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,Sw=6e4;jt=(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 n=new Error("").stack;throw Oc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Js=nt(async(s,e={},t={},r=Jr)=>{try{let n=ht.default.delete(s).send(e).timeout(r).set(t);br(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return jt("failed to delete request",n,{url:s})}}),Ve=nt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await am(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return jt("failed to post request",i,{url:s})}});Xs=nt(async(s,e,t,r={},n=Jr)=>{let i=ht.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),br(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return jt("failed to post request",o,{url:s})}});Ys=nt(async(s,e,t)=>{try{return(await _c(s,e,t)).text}catch(r){return jt("failed to getText request",r,{url:s,query:e})}}),Lc=nt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await am(s,e,t,r,n)).text}catch(i){return jt("failed to post request",i,{url:s})}}),Te=nt(async(s,e,t,r,n)=>{try{return(await _c(s,e,t,r,n)).body}catch(i){return jt("failed to get request",i,{url:s,query:e})}}),xw=nt((s,e,t,r)=>_c(s,e,t,r)),Aw=nt(async s=>{let e=ht.default.head(s).timeout(Jr);br(e);try{return await e}catch(t){return jt("failed to head request",t,{url:s})}}),Dc=nt(async(s,e,t={},r=Jr)=>{let n=ht.default.put(s).send(e).timeout(r).set(t);br(n);try{return(await n).body}catch(i){return jt("failed to put request",i,{url:s})}}),Nc=nt(async s=>{Oc.info("start to download",{url:s});let e=ht.default.get(s).set("User-Agent","Testim.io").timeout(Sw).buffer(!0).parse(Iw);br(e);try{let t=await e;return Oc.info("finished to download",{url:s}),t}catch(t){return jt("failed to download",t,{url:s})}}),Mc=nt.isNetworkHealthy,Fc=nt.didNetworkConnectivityTestFail});function yt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=$t.resolve(__dirname,"../../"):s=$t.resolve(__dirname,""),s):process.cwd()}function ki(s,e){return De(s)?e||$t.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||$t.basename(s)}function rt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function jc(){try{return Id.node}catch{return""}}async function um(s,e,t=!0){let r=await it.promises.readdir(s,{withFileTypes:!0});await it.promises.mkdir(e,{recursive:t});for(let n of r){let i=$t.join(s,n.name),o=$t.join(e,n.name);n.isDirectory()?await um(i,o):await it.promises.copyFile(i,o)}}async function ye(s){try{return await it.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var $t,cm,lm,it,Cw,Wt,Je,Oi,Uc,ot,Bc,pm=S(()=>{"use strict";$t=I(require("node:path"));yc();Ti();cm=I(require("unzip-stream")),lm=I(require("p-retry")),it=require("node:fs"),Cw=3;Wt=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Ke));return(0,lm.default)(()=>e.download(s),{retries:Cw,factor:1})},Je=async(s,e)=>{let t=await Wt(s);return it.promises.writeFile(e,t.body)};Oi=async(s,e)=>{let t=ki(s,e);return De(s)?Je(s,t):it.promises.copyFile(s,t)},Uc=async s=>De(s)?Wt(s):it.promises.readFile(s),ot=async(s,e)=>(0,it.createReadStream)(s).pipe(cm.Extract({path:e})),Bc=s=>(0,it.statSync)(s).size/1e6});var Vt={};z(Vt,{APPIUM_SESSION_MESSAGE:()=>Hc,CLI_MODE:()=>K,MOBILE_APP_SOURCE:()=>_i,MOBILE_RUN_SKIP_REASON:()=>Gc,OPERANDS:()=>Zs,REGION_CONFIG:()=>Yr,X_HEADER_RUNNER_ID:()=>qc,gridMessages:()=>bt,gridTypes:()=>_,mobileWeb:()=>Wc,runnerStatus:()=>$c,runnerTestStatus:()=>fe,socketEventTypes:()=>kt,stepResult:()=>Xr,test:()=>Vc,testRunStatus:()=>Qs,testStatus:()=>Xe,timeoutMessages:()=>Ae});var Ae,Qs,$c,fe,Xe,bt,Wc,Vc,kt,K,_,Xr,_i,Gc,Hc,qc,Yr,Zs,ae=S(()=>{"use strict";Ae={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"},$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"},_={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},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"},_i={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",Yr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"},Zs=(t=>(t.AND="AND",t.OR="OR",t))(Zs||{})});function en(s,e){var t,r,n,i,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(n=s.browser)==null?void 0:n.toLowerCase()]:(i=s.testConfigNames)!=null&&i.length||(o=s.testConfigIds)!=null&&o.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(c=>{var l;return(l=c.runConfig)==null?void 0:l.browserValue}))]:[(a=s.browser)==null?void 0:a.toLowerCase()]}function Pw(){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 tn,dm,Ye,kw,Ow,_w,Lw,Dw,zc,Kc,mm=S(()=>{"use strict";ae();tn=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},dm=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Xe.QUARANTINE&&!dm(e)&&!e.runQuarantinedTests;kw=s=>Boolean(s.loginMode),Ow=s=>Boolean(s.tunnelOnlyMode),_w=s=>Boolean(s.createPrefechedData),Lw=s=>Boolean(s.installLazyDepsMode),Dw=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 Di(s=0){return Li.default.duration(s).format("HH:mm:ss.SSS")}function Jc(s=0){return Li.default.duration(s).asSeconds()}var Li,fm,Ni,gm=S(()=>{"use strict";Li=I(require("dayjs")),fm=I(require("dayjs/plugin/duration"));Li.default.extend(fm.default);Ni=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 rn,Qr,Zt,hm,Zr,ym=S(()=>{"use strict";ae();rn=s=>!(!s||"fileName"in s),Qr=(s,e)=>{if(e===_.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"},hm=s=>s===_.TESTIM_TVC,Zr=(s,e)=>hm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Xc(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 bm=S(()=>{"use strict"});var X={};z(X,{OSS:()=>es,TESTIM_BROWSER_DIR:()=>Gt,buildBasicHeader:()=>hc,calcPercentile:()=>Ui,copyDir:()=>um,delay:()=>pe,doesPathExist:()=>ye,download:()=>Wt,downloadAndSave:()=>Je,extractElementId:()=>Ne,formatTimeoutDuration:()=>Ni,getArgsOnRemoteRunFailure:()=>Pw,getBrowserInfo:()=>Mw,getCdpAddressForHost:()=>vr,getCliLocation:()=>yt,getDuration:()=>Di,getDurationSec:()=>Jc,getEnginesVersion:()=>jc,getEnvironmentGitBranch:()=>wr,getLinksFromUnescapeHTML:()=>on,getLocalFileSizeInMB:()=>Bc,getMemorySnapshot:()=>Xc,getPlanType:()=>Fi,getRunConfigByBrowserName:()=>sn,getRunnerVersion:()=>rt,getSource:()=>Oi,getSourceAsBuffer:()=>Uc,getSourcePath:()=>ki,getTestUrl:()=>ze,getUniqBrowsers:()=>en,groupTestsByRetries:()=>Qc,guid:()=>re,hasTestPlanFlag:()=>tn,isAgentMode:()=>Dw,isAppFromDevice:()=>rn,isAppFromDeviceDisabled:()=>Zr,isCreatePrefetchedDataMode:()=>_w,isInstallLazyDepsMode:()=>Lw,isLoginMode:()=>kw,isMobileProject:()=>Zt,isPromise:()=>Cc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>dm,isTestimVirtualGrid:()=>hm,isTunnelOnlyMode:()=>Ow,isURL:()=>De,promiseAbort:()=>Pc,promiseFromCallback:()=>Qt,promiseMap:()=>se,promiseTimeout:()=>le,removePropertyFromObject:()=>Mi,replaceArgsWithNoDashes:()=>zc,sanitizeNumberValue:()=>Tr,shouldBlockVirtualIosBuild:()=>Qr,spreadObjectToArgs:()=>Kc,unescapeHTML:()=>nn,unzipFile:()=>ot});function Tr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function Mw(s){return s=s.toLowerCase(),Yc.find(e=>e.browserValue===s)}function sn(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Yc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Yc[0],n=es.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=es.find(i=>i.sl.platform===e.platform):e.platformName&&(n=es.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=es.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=es.find(i=>i.bs.platform===t.platform))),ts.merge(r,n)}function wr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Mi(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Mi(s[r],e,t))}function Ne(s){return s.ELEMENT||s[Jt]}function Fi(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 ts.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=ts.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function nn(s){return Em.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function on(s){return[...Em.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function vr(s,e){let t=await Promise.resolve().then(()=>(Ge(),Ke));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 wm,ts,vm,Sm,Nw,Gt,Tm,es,Yc,Ui,Em,B=S(()=>{"use strict";wm=I(require("os")),ts=I(require("lodash")),vm=I(require("path")),Sm=require("linkedom");Hr();pm();mm();gm();yc();kc();ym();bm();Nw=wm.homedir(),Gt=vm.join(Nw,".testim-browser-profile"),Tm="133",es=[{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"}}],Yc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:Tm},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:Tm},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"}];Ui=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};Em=new Sm.DOMParser});var Zc={};z(Zc,{$schema:()=>Fw,default:()=>Ww,definitions:()=>Uw,properties:()=>$w,required:()=>jw,type:()=>Bw});var Fw,Uw,Bw,jw,$w,Ww,Im=S(()=>{Fw="http://json-schema.org/draft-07/schema#",Uw={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}}}},Bw="object",jw=["entries"],$w={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Ww={$schema:Fw,definitions:Uw,type:Bw,required:jw,properties:$w}});async function Om(){try{return await le(Bi.promises.readFile(Vi()).then(async s=>{let e=await km;return Hw(e,s)}),3e4)}catch{return{}}}function Hw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=ss.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Ot(s,e,t=Vw,r=void 0){return async()=>{if(!Am)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await tl(e);if(i)return an.debug("cache hit:",{fnName:e}),i;if(an.debug("cache miss:",{fnName:e}),!Cm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await qw(e,o,t),o}}async function tl(s){let t=(await Gi)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function qw(s,e,t){if(el)throw an.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 Gi;r[s]={value:e,expiry:Date.now()+t},Pm=new Promise(n=>{Wi=n}),Gw(r)}catch{an.error("failed updating cache")}}async function ns(){let s=await Gi;Object.keys(s).forEach(e=>{delete s[e]})}function _m(s){Am=s}function zw(s=!0){Cm=s}async function Lm(){try{return el=!0,await Pm}finally{el=!1}}function Dm(s){$i=s,Gi=Om()}var Bi,ji,ss,Rm,an,$i,xm,Wi,Am,Cm,el,Pm,km,Vw,Vi,Gi,Gw,Nm,Mm,xx,Fm,er=S(()=>{"use strict";Bi=I(require("fs")),ji=I(require("path")),ss=I(require("crypto"));B();Rm=require("lodash");W();an=P("local cache"),$i=ji.resolve(yt(),"testim-cache"),Am=!0,Cm=!0,el=!1,Pm=new Promise(s=>{Wi=s}),km=new Promise(s=>{xm=s}),Vw=1e3*60*60*3,Vi=()=>ji.resolve(ji.resolve($i,"testim.cache"));Gi=Om(),Gw=(0,Rm.debounce)(async s=>{let e;try{let t=await km,r=ss.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=ss.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye($i)||await Bi.promises.mkdir($i,{recursive:!0}),await Bi.promises.writeFile(Vi(),a)}catch(t){an.error("failed saving cache",{err:t}),e=t}Wi(e?{success:!1,error:e}:{success:!0})},200);Nm=xm,Mm=_m.bind(void 0,!1),xx=_m.bind(void 0,!0),Fm=()=>zw(!1)});function Hi(){return{cliLocation:yt(),userInfo:is.userInfo(),platform:is.platform(),release:is.release()}}var is,rl=S(()=>{"use strict";is=I(require("node:os"));B()});function Kw(s){try{return qi.resolve(qi.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=Kw(s);return require(e)}var qi,cn=S(()=>{"use strict";qi=I(require("path"))});function Jw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Xw(s){return/The "to" argument must be of type string./.exec(s)}function $m(s,e,t){let r=Jw(s),n=Xw(s);return r||n?(jm.info("Failed to install package due to insufficient write access",{...Hi(),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 rl(s){try{return tr(s)}catch{return!1}}function jm(s,e){return require(cn.join(s,`./node_modules/${e}/package.json`)).version}function $m(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=$m(s[e]);if(t)return t}}function Wm(s){let e=require(cn.join(s,"package.json"));if(!("exports"in e))return"";let t=$m(e);if(!t)throw new Ai(e.name);return t}async function qi(s,e,t){let r=cn.join(s,"npm-shrinkwrap.json"),n=cn.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await ye(r)&&(await tl.promises.rename(r,n),i=!0)}catch{}return await Fm(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw Bm(o.stderr,s,e)?new Kr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await tl.promises.rename(n,r)}catch{}}}function sl(s,e,t,r,n=!0){return new Promise((i,o)=>{var h,g,y,T;let a=t?["--proxy",t]:[],c=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},l="",m="",d=["--no-save","--no-package-lock","--no-prune","--no-audit","--progress=false"];n&&d.push("--prefer-offline");let u="npm";process.platform==="win32"&&(u="npm.cmd",c.shell=!0);let f=(0,Hi.spawn)(u,["i","--prefix",s,...d,...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",v=>{l+=v}),(T=f.stderr)==null||T.on("data",v=>{m+=v}),f.on("close",v=>{var b,w;if(v){n&&sl(s,e,t,r,!1).then(i).catch(o);let S;try{let A=(b=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(m))==null?void 0:b[1],D=(w=/No matching version found for (\S+)@/gm.exec(m))==null?void 0:w[1];A||D?S=`404 Not Found - GET https://registry.npmjs.org/${D??A} - Not found`:Bm(m,s)?S=`insufficient write access in location ${s}`:S=`Npm Installation closed with exit code ${v} with error: ${m}`}catch(A){S=`Npm Install closed with exit code ${v}
9
+ `),!0):!1}function nl(s){try{return tr(s)}catch{return!1}}function Wm(s,e){return require(ln.join(s,`./node_modules/${e}/package.json`)).version}function Vm(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=Vm(s[e]);if(t)return t}}function Gm(s){let e=require(ln.join(s,"package.json"));if(!("exports"in e))return"";let t=Vm(e);if(!t)throw new Ci(e.name);return t}async function Ki(s,e,t){let r=ln.join(s,"npm-shrinkwrap.json"),n=ln.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await ye(r)&&(await sl.promises.rename(r,n),i=!0)}catch{}return await Bm(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw $m(o.stderr,s,e)?new Kr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await sl.promises.rename(n,r)}catch{}}}function il(s,e,t,r,n=!0){return new Promise((i,o)=>{var h,g,y,T;let a=t?["--proxy",t]:[],c=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},l="",m="",d=["--no-save","--no-package-lock","--no-prune","--no-audit","--progress=false"];n&&d.push("--prefer-offline");let u="npm";process.platform==="win32"&&(u="npm.cmd",c.shell=!0);let f=(0,zi.spawn)(u,["i","--prefix",s,...d,...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",w=>{l+=w}),(T=f.stderr)==null||T.on("data",w=>{m+=w}),f.on("close",w=>{var b,v;if(w){n&&il(s,e,t,r,!1).then(i).catch(o);let E;try{let A=(b=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(m))==null?void 0:b[1],D=(v=/No matching version found for (\S+)@/gm.exec(m))==null?void 0:v[1];A||D?E=`404 Not Found - GET https://registry.npmjs.org/${D??A} - Not found`:$m(m,s)?E=`insufficient write access in location ${s}`:E=`Npm Installation closed with exit code ${w} with error: ${m}`}catch(A){E=`Npm Install closed with exit code ${w}
10
10
  err: ${A}
11
- stdout: ${l} stderr: ${m}`}Um.info(`Npm Install closed with exit code ${v}`,{message:S,stderr:m}),o(new Ct(S))}else i(l)}),setTimeout(()=>{try{f.kill()}finally{o(new ce)}},r)})}async function Vm(){try{return(await Fm("npm -v")).stdout.trim()}catch{return""}}var tl,cn,Mm,Hi,Fm,Um,os=E(()=>{"use strict";tl=I(require("fs")),cn=I(require("path"));B();Mm=require("util"),Hi=require("child_process");$();el();an();Y();Fm=(0,Mm.promisify)(Hi.exec),Um=P("cli-service")});var U,Hm,qm,zm,Xw,Yw,Qw,Gm,zi,il,O,de=E(()=>{"use strict";U=I(require("rox-node")),Hm=I(require("node-fetch")),qm=require("eventsource");$();B();oe();zm=P("FeatureFlagsService"),Xw=!We&&!0&&!_d,Yw=2e4,Qw=60*60*24,Gm=["labs","disabled","enabled"],zi=class extends U.default.RoxString{constructor(e="disabled"){super(e,Gm)}getValue(){let e=super.getValue();return Gm.includes(e)?e:(zm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},il=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 zi("labs"),highSpeedMode:new zi,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,headSpinTdcEnableFlagCapability:new U.default.Flag,enableBatchTDC:new U.default.Flag,enableBatchHeadSpin: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,n;if(!Xw)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,c)=>(0,Hm.default)(a,{...c,agent:o}),n=function(a){return new qm.EventSource(a,{fetch:r})}}let i={fetchIntervalInSec:Qw,fetchFunction:r,eventSourceImpl:n};return le(U.default.setup(kd,i),Yw).catch(o=>zm.error("failed to get feature flag status",o))}},O=new il});var Ym={};z(Ym,{install:()=>ev,isReady:()=>rv,start:()=>tv});var Km,Jm,Xm,al,ol,Zw,ev,tv,rv,Qm=E(()=>{"use strict";Km=I(require("fkill")),Jm=I(require("p-retry"));os();Ge();B();an();de();Xm="chromedriver",al=9515,ol=`http://localhost:${al}/wd/hub`,Zw=[`--port=${al}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],ev=async()=>{let s=O.flags.chromedriverCdnBinariesUrl.getValue(),e=De(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await qi(ht(),`${Xm} --detect_chromedriver_version ${e}`)},tv=async()=>{process.env.NODE_OPTIONS="",await(0,Km.default)(`:${al}`,{silent:!0}),await tr(Xm).start(Zw,!0)},rv=async({chromeBinaryLocation:s})=>{await(0,Jm.default)(async()=>{var n;let e=await Te(`${ol}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Ve({url:`${ol}/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 Js(`${ol}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var un={};z(un,{getSessionPlayerFolder:()=>pl,prepareChromeDriver:()=>ln,prepareCustomExtension:()=>ll,prepareExtension:()=>ul,preparePlayer:()=>Sr});async function ll(s,e=!1){if(!s)return;if(De(s)){let n=as.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await sv(s)>cl&&!e)throw new C(Zm);return await Je(s,n),n}let t=as.resolve(s);if(!tf.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(Mc(t)>cl&&!e)throw new C(Zm);return t}async function sv(s){let e=(Ge(),qe(Ke));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Ki.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function ul(s){Ki.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Pi(t)}));return kt(()=>se(e,({location:t,path:r})=>ki(t,r)),"prepareExtension",sf,e)()}async function ln(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(Qm(),Ym));try{await i.install(),await i.start(),t||await i.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof Kr||(Ki.error(a,{...s,...Vi(),error:(0,rf.serializeError)(o)}),console.log(`
11
+ stdout: ${l} stderr: ${m}`}jm.info(`Npm Install closed with exit code ${w}`,{message:E,stderr:m}),o(new Pt(E))}else i(l)}),setTimeout(()=>{try{f.kill()}finally{o(new ce)}},r)})}async function Hm(){try{return(await Bm("npm -v")).stdout.trim()}catch{return""}}var sl,ln,Um,zi,Bm,jm,os=S(()=>{"use strict";sl=I(require("fs")),ln=I(require("path"));B();Um=require("util"),zi=require("child_process");W();rl();cn();Y();Bm=(0,Um.promisify)(zi.exec),jm=P("cli-service")});var U,zm,Km,Jm,Yw,Qw,Zw,qm,Ji,al,O,de=S(()=>{"use strict";U=I(require("rox-node")),zm=I(require("node-fetch")),Km=require("eventsource");W();B();oe();Jm=P("FeatureFlagsService"),Yw=!We&&!0&&!Dd,Qw=2e4,Zw=60*60*24,qm=["labs","disabled","enabled"],Ji=class extends U.default.RoxString{constructor(e="disabled"){super(e,qm)}getValue(){let e=super.getValue();return qm.includes(e)?e:(Jm.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 Ji("labs"),highSpeedMode:new Ji,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,headSpinTdcEnableFlagCapability:new U.default.Flag,enableBatchTDC:new U.default.Flag,enableBatchHeadSpin: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,n;if(!Yw)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,c)=>(0,zm.default)(a,{...c,agent:o}),n=function(a){return new Km.EventSource(a,{fetch:r})}}let i={fetchIntervalInSec:Zw,fetchFunction:r,eventSourceImpl:n};return le(U.default.setup(_d,i),Qw).catch(o=>Jm.error("failed to get feature flag status",o))}},O=new al});var Zm={};z(Zm,{install:()=>tv,isReady:()=>sv,start:()=>rv});var Xm,Ym,Qm,ll,cl,ev,tv,rv,sv,ef=S(()=>{"use strict";Xm=I(require("fkill")),Ym=I(require("p-retry"));os();Ge();B();cn();de();Qm="chromedriver",ll=9515,cl=`http://localhost:${ll}/wd/hub`,ev=[`--port=${ll}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],tv=async()=>{let s=O.flags.chromedriverCdnBinariesUrl.getValue(),e=De(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await Ki(yt(),`${Qm} --detect_chromedriver_version ${e}`)},rv=async()=>{process.env.NODE_OPTIONS="",await(0,Xm.default)(`:${ll}`,{silent:!0}),await tr(Qm).start(ev,!0)},sv=async({chromeBinaryLocation:s})=>{await(0,Ym.default)(async()=>{var n;let e=await Te(`${cl}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Ve({url:`${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 Js(`${cl}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var pn={};z(pn,{getSessionPlayerFolder:()=>ml,prepareChromeDriver:()=>un,prepareCustomExtension:()=>pl,prepareExtension:()=>dl,preparePlayer:()=>Er});async function pl(s,e=!1){if(!s)return;if(De(s)){let n=as.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await nv(s)>ul&&!e)throw new C(tf);return await Je(s,n),n}let t=as.resolve(s);if(!sf.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(Bc(t)>ul&&!e)throw new C(tf);return t}async function nv(s){let e=(Ge(),qe(Ke));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Xi.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function dl(s){Xi.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:ki(t)}));return Ot(()=>se(e,({location:t,path:r})=>Oi(t,r)),"prepareExtension",of,e)()}async function un(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(ef(),Zm));try{await i.install(),await i.start(),t||await i.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof Kr||(Xi.error(a,{...s,...Hi(),error:(0,nf.serializeError)(o)}),console.log(`
12
12
  1. If you don't have Chrome, please install it from https://www.google.com/chrome.
13
13
  2. If Chrome is installed, please verify it's binary directory:
14
14
  - installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
15
15
  - exists in your PATH environment variables.
16
16
  3. Try adding --chrome-binary-location flag to Testim CLI specifying the exact location of chrome binary in your computer (e.g on Windows "C:/Program Files/Google/Chrome/Application/chrome.exe").
17
- 4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),o}}async function nv(){let s=xt==="staging"?`${mt}/Staging-LATEST_VERSION`:`${mt}/sessionPlayer_LATEST_RELEASE`;return(await $t(s)).body.toString("utf8")}function iv(){return`${mt}/dev-sessionPlayer.zip`}async function ov(s,e){if(!De(s)||De(s)&&e||We)return s;let t=await nv();return`${s}-${t}${xt==="staging"?".zip":""}`}function pl(){let s=ht();return as.resolve(s,"testim-bin")}function av(){let s=pl();return as.resolve(s,"sessionPlayer.zip")}async function nf(s,e,t=!1){try{return await ki(s,e),await ot(e,pl())}catch(r){if(t)throw r;return await nf(s,e,!0)}}async function Sr(s,e){Ki.info("prepare player",{location:s,canary:e});let t=av();return kt(async()=>{let r=xt==="development"?iv():await ov(s,e);return await nf(r,t),{}},"preparePlayer",sf,[s,e,t])()}var ef,tf,as,rf,Ki,sf,cl,Zm,pn=E(()=>{"use strict";ef=I(require("ms")),tf=I(require("node:fs")),as=I(require("node:path"));oe();er();rf=require("serialize-error");$();el();Y();B();Ki=P("prepare runner and testim start"),sf=(0,ef.default)("0.5 day"),cl=16,Zm=`The size of the custom extension is more than ${cl}MB`});function cv(){let s=dn.type().toLowerCase();return s==="darwin"?dn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?dn.arch()==="x64"?"win64":"win32":"linux"}async function Xi(){let s=cv(),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 C(`Unsupported platform: ${s}`);let r=parseInt(mn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},i={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},o=`${e}/${t[s]}/${mn}/${n[s]}.zip`,a=Ji.join(dl,n[s]),c=`${a}.zip`,l=Ji.join(a,i[s]);if(await ye(l))return l;if(!await ye(c)){let d=(0,ml.default)("Downloading Chromium").start();try{await of.promises.mkdir(dl),await Je(o,c)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw d.fail(f),new Error(f)}d.succeed()}let m=(0,ml.default)("Extracting Chromium").start();try{await ot(c,dl)}catch(d){let u=`Failed to extract Chromium: ${d.message}`;throw m.fail(u),new Error(u)}return m.succeed(),l}var of,dn,Ji,ml,mn,dl,fl=E(()=>{"use strict";of=I(require("fs")),dn=I(require("os")),Ji=I(require("path")),ml=I(require("ora"));Y();B();mn="1000968",dl=Ji.join(Vt,`chrome-${mn}`)});async function lf(s,e){return Er=s,bl=e,await gl()}function uf(s,e){Er=e.projectId,bl=e.token,fn=e.userAccessKey,at=s.token,hn=Tl(at),yn=s.refreshToken,hl=s.ngrokToken,yl=s.isNgrokWhitelisted,af=e.publicIp,cf=e.initializedFromCache}function uv(s=Er,e=bl){return kt(()=>(gn.info("request to get cli token from server"),Ve({url:`${he()}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",lv*10,{projectId:s,token:e})()}async function pv(){gn.info("request to refresh JWT cli token from server");let s=await Ve({url:`${he()}/auth/refreshToken`,body:{token:at,refreshToken:yn}});return at=s.token,hn=Tl(at),s.refreshToken&&(yn=s.refreshToken),at}async function gl(){try{let s=await uv();return gn.info("successfully get cli token from server"),at=s.token,hn=Tl(at),yn=s.refreshToken,hl=s.ngrokToken,yl=s.isNgrokWhitelisted,at}catch(s){throw s.message.includes("Unauthorized")?new C("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."):(gn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Er}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function Tl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Ot(){if(!hn)return gl();let s=O.flags.accessTokenExpiryMargin.getValue();if(hn<Date.now()+4*s)try{return await pv()}catch(e){return gn.error("failed to refresh token, executing fallback",e),gl()}return at}function Yi(){return yn}function Ir(){return at?{uid:require("jsonwebtoken").decode(at).id,ngrokToken:hl,isNgrokWhitelisted:yl}:{}}async function Qi(){if(!fn||!Er)return;if(await wl({userAccessKey:fn,projectId:Er}))return fn;let e=`user access key "${fn}" is invalid for project "${Er}"`;throw new C(e)}function Zi(){return af}function eo(){return cf}var gn,at,hn,yn,hl,yl,Er,bl,fn,af,cf,lv,ct=E(()=>{"use strict";oe();Ge();er();Y();$();ge();de();gn=P("testim-custom-token"),Er=null,bl=null,lv=5*60*1e3});function dv(s){if(s.protocol)return s.protocol;if([_.TESTIM_PRIVATE,_.TESTIM,_.BROWSERSTACK,_.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([_.TESTIM_ENTERPRISE,_.TESTIM_LAMBDATEST,_.DEVICE_FARM].includes(s.type)){let e=pf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function mv(s){let e=pf.exec(s);return e==null?void 0:e[3]}function ro(s){var w,S,A,D,V,x,R,L,M,G,W;let e=s&&mv(s.host),t=s.port,r=s.path,n=s&&dv(s),i=s.token,o=s.slotId,a=(w=s.hybrid)==null?void 0:w.tunnel,c=(S=s.external)==null?void 0:S.user,l=(A=s.external)==null?void 0:A.key,m=s.type,d=m===_.HYBRID?a&&((x=(V=(D=s.hybrid)==null?void 0:D.external)==null?void 0:V[s.hybrid.tunnel])==null?void 0:x.user):c,u=m===_.HYBRID?a&&((M=(L=(R=s.hybrid)==null?void 0:R.external)==null?void 0:L[s.hybrid.tunnel])==null?void 0:M.key):l,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(G=s.mobileTokens)==null?void 0:G.androidToken,T=(W=s.mobileTokens)==null?void 0:W.iosToken,v=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:c,key:l,type:m,name:f,provider:g,tunnelUser:d,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:v,isSupportGrid:b}}async function gv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(c){throw lt.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(yt.UNKNOWN)}if(lt.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw lt.error("invalid response - get grid",{res:o}),new Error(yt.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,gf(n));let c=ro(o.grid);return fv(t,e,c.gridId,c.slotId,r,c.isSupportGrid),c}throw o.code==="not-found"?new st(yt.NOT_FOUND):o.code==="no-available-slot"?new Yt(`Failed to run test on ${r} - concurrency limit reached`):(lt.error("invalid code error response - get grid",{res:o}),new st(yt.UNKNOWN))}function mf(s){return xl(s)}async function ff(s,e,t){let n=(t||await mf(s)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return ro(n)}async function hv(s,e,t){let n=(t||await mf(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return ro(n)}async function vl(s,e){let t=bn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete bn[s],!a){if(!r){lt.warn("failed to find grid slot id",{projectId:e});return}lt.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await El(o,e,r,n,i)}catch(c){lt.error("failed to release slot",{projectId:e,err:c})}}}async function yv(s){let e=Object.values(bn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid)try{await Sl(s,e)}catch(t){lt.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}function bv(s){df=global.setInterval(yv,1e4,s)}async function Tv(s){let e=Object.keys(bn);if(e.length){lt.warn("not all slots released before end runner flow",{projectId:s});try{await se(e,t=>vl(Number(t),s))}catch(t){lt.error("failed to release all slots",{err:t,projectId:s})}}}async function wv(s){await Tv(s),clearInterval(df)}function vv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function Sv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function gf(s){let t=(()=>to.isEmpty(s.testobjectSauce)?to.isEmpty(s.saucelabs)?to.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=vv(t,s),c=Sv(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:c,key:a,gridId:re()}}async function hf(s,e){let t=s.company.companyId;return await ff(t,e.gridId,s.allGrids)}async function yf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:c}=s;if(n||o||i)return{mode:"local"};if(r)return gf(s);let l=t==null?void 0:t.companyId;if(a)return ff(l,a,e);if(c)return hv(l,c,e);if(en(s)||s.tunnelOnlyMode){lt.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new st("Missing host or grid configuration")}async function bf(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:c,localTmaUrl:l,useLocalChromeDriver:m,useChromeLauncher:d,company:u}=t,f=Boolean(m||d||l),h=u==null?void 0:u.companyId;return gv(o,h,r,s,t,()=>Rl({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:i,testResultId:n}))}var to,lt,bn,pf,df,fv,Tn,Tf,cs=E(()=>{"use strict";to=I(require("lodash"));ge();$();B();ae();Y();lt=P("grid-service"),bn={},pf=/(^(https?):\/{2})?(.*)/,df=null;fv=(s,e,t,r,n,i)=>{bn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};Tn={start:bv,end:wv};Tf=async(s={},e={},t={},r={},n={})=>{var g,y,T;let{company:{companyId:i}={},project:o}=s,{gridId:a,type:c}=e,l=s.browser||t.browserValue,m=Boolean(s.tunnel),{maxRetries:d,currentRetry:u}=n;if(!a||!c||((c===_.TESTIM_LAMBDATEST||c===_.LAMBDATEST)&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e,i,o)),c!==_.HYBRID||!i||!l||!d||!u))return e;let f=await Il({companyId:i,gridId:a,maxRetries:d,currentRetry:u,browser:l,usingTunnel:m});lt.info("handling hybrid grid",{response:f,companyId:i});let h=ro({...e,...f.connectionDetails,provider:f.provider});return f.provider!=="lambdatest"&&((y=r.disable)==null||y.call(r)),f.provider==="lambdatest"&&await((T=r.enableIfNeeded)==null?void 0:T.call(r,h,i,o)),h}});function vn(){return so||"master"}function wf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){so="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){so=s.branch||s;return}so=e?"master":void 0}var so,Al=E(()=>{"use strict";Y()});function If(s){We||(s!=null&&s.userId||(s={anonymousId:"runnerId"}),Ef.identify(s))}function bt(s,e){return ls("ci",s,e)}function ls(s,e,t){if(We)return;let r=s?{userId:s}:{anonymousId:"runnerId"};Ef.track(Object.assign(r,{event:e,properties:t}))}var Sf,Ef,us=E(()=>{"use strict";oe();Sf=require("@segment/analytics-node"),Ef=new Sf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1})});var Rf={};z(Rf,{isCi:()=>ps});var ps,no=E(()=>{"use strict";ps=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Af(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Cf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:l,user:m,lightweightMode:d,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Af({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:xf(l,m),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},d);bt("test-run-ci",y)}function Pf({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,source:m,user:d,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let v=Af({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:xf(m,d),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){bt("test-run-ci-success",v);return}bt("test-run-ci-fail",{...v,failureReason:n.failureReason})}catch(v){f.error("failed to update test end analytics",{err:v})}}function kf(s){bt("batch-run-ci",s)}var xf,Cl=E(()=>{"use strict";us();no();xf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ps&&e?"ci-with-user":ps?"ci":e?"cli-with-user":s});var Pl,ue,_f=E(()=>{"use strict";Pl=class{static colorString(e,t){return`${e}${t}${Pl.Reset}`}},ue=Pl;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 En,kl,Ev,Ol,Iv,io,oo,ao,co,lo,uo=E(()=>{"use strict";B();ae();En=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===fe.FAILED},kl=s=>{let{status:e}=s;return e===fe.ABORTED},Ev=s=>{let{status:e}=s;return e===fe.PASSED},Ol=s=>s.runnerStatus===Uc.SKIPPED,Iv=s=>s.testStatus===Xe.EVALUATING,io=(s,e)=>Object.values(s).filter(t=>{var r,n;return Ol(t)&&(Ye(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,oo=s=>Object.values(s).filter(e=>En(e)&&Iv(e)).length,ao=s=>Object.values(s).filter(En),co=s=>Object.values(s).filter(Ev),lo=s=>Object.values(s).filter(kl)});function xv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var _l,po,Rv,mo,Lf=E(()=>{"use strict";_l=I(require("lodash"));$();uo();po=P("debug-reporter"),Rv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],mo=class{constructor(e){this.options=e}onTestStarted(e,t){po.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;po.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:c,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{..._l.default.omit(this.options,Rv),company:_l.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let c=xv(process.argv);po.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,i){let o=co(e).length,a=Object.keys(e).length-o;po.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Ll,_t,In=E(()=>{"use strict";ae();Ll=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===_.DEVICE_FARM}},_t=new Ll});var Nl={};z(Nl,{Reporter:()=>Av});var sr,Rn,Rr,fo,Df,Dl,Av,Ml=E(()=>{"use strict";sr=I(require("chalk")),Rn=I(require("lodash"));B();ae();In();uo();Rr={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:fo}=Wt,Df="device",Dl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${sr.default.underline(ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?fe.PASSED:fe.FAILED,n=`(${e.testId})`,i=Rr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Li(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=ze(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Rr.error("Failed runs are:")),console.log(Rr.error(t.join(`
18
- \r`)))}onTestPlanFinished(e,t,r,n,i){let o=ao(e),a=co(e),c=lo(e),l=a.length,m=c.length,d=o.length,u="",f="";if(_t.isTestStatusEnabled){let v=oo(e);u=` FAILED-EVALUATING: ${v}`,d-=v,f=` SKIPPED: ${io(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=Rr[d?"error":"success"],T=`PASSED: ${l} FAILED: ${d}${u} ABORTED: ${m}${f} Duration: ${Li(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=Rn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Rn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Rn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Rn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let c=u=>{u.forEach((f,h)=>{var v;let g=(v=f.testData)!=null&&v.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`,T="";f.testOptimization?T=` [${f.testOptimization.reason}]`:Ye(f,this.options)&&(T="-quarantine"),console.log(" ",h+1,":",`${f.name}${T}`,y,g)})},l=a?`config '${a}'`:"default configs",m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",d=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${d} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===fo.APPIUM?Df:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===fo.APPIUM?Df:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} 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 n=this.options.grid||this.options.gridId,i=this.options.mode===fo.APPIUM?"device":"browser";if(n)console.log(Rr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(Rr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===fo.APPIUM?"Appium":"Selenium";console.log(Rr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},Av=Dl});var Bl={};z(Bl,{Reporter:()=>Lv});function Cv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function Pv(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 kv(s){return`${s.visitedUrlsJson||""}`}async function Ov(s,e,t,r,n,i){function o(u){let f=ze(s,t,u.testId,u.resultId,r),h={$:{name:Cv(u),classname:n,time:qc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(En(u)||kl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=En(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Ol(u)&&Ye(u,i)&&_t.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=Pv(u),h["visited-urls-json"]=kv(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},v={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(y),failures:m(y),timestamp:c(e)};if(_t.isTestStatusEnabled){v.skipped=io(y,i);let b=oo(y);v.failures-=b,v["failure-evaluating"]=b}return{$:v,testcase:Object.keys(y).map(b=>o(y[b]))}}function c(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function l(u){return Object.keys(u).length}function m(u){return ao(u).length+lo(u).length}let d={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Ul.Builder().buildObject(d)}catch(u){return _v(u)}}function _v(s){let e=new Ul.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 Ul,Nf,Fl,Lv,jl=E(()=>{"use strict";Ul=I(require("xml2js"));B();Nf=require("fs");In();uo();Fl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await Ov(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Nf.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};Lv=Fl});var Mf={};z(Mf,{Reporter:()=>Dv});function ds(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 $l,Wl,Dv,Ff=E(()=>{"use strict";$();$l=P("team-city-reporter");Wl=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return ds(n)}onTestStarted(e,t,r,n){if(r){$l.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,i,o){if(i){$l.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ds(t)}' details='${ds(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){$l.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ds(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ds(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ds(t)}']`)}},Dv=Wl});var Uf={};z(Uf,{Reporter:()=>Nv});var Vl,Nv,Bf=E(()=>{"use strict";Vl=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},Nv=Vl});function ho(s){let{platform:e}=process;e==="win32"?(0,go.exec)(`start chrome ${s}`):e==="darwin"?(0,go.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,go.exec)(`google-chrome ${s}`)}var go,Gl=E(()=>{"use strict";go=require("child_process")});var jf={};z(jf,{Reporter:()=>Mv});var Hl,Mv,$f=E(()=>{"use strict";B();Gl();Hl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return ho(t)}},Mv=Hl});var ql,Q,Lt=E(()=>{"use strict";Lf();ql=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 mo(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Ml(),Nl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(jl(),Bl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Ff(),Mf)),r.includes("console")&&Promise.resolve().then(()=>(Ml(),Nl)),r.includes("junit")&&Promise.resolve().then(()=>(jl(),Bl)),r.includes("json")&&Promise.resolve().then(()=>(Bf(),Uf)),r.includes("chrome")&&Promise.resolve().then(()=>($f(),jf))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,i){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var i;let n=t==null?void 0:t(...r);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||r))}}},Q=new ql});async function zl(s,e,t){let r=ms[s];if(!r)return;let{slotId:n}=r;if(delete ms[s],!n){Tt.warn("failed to find slot slot id",{companyId:e,workerId:s});return}Tt.info("release slot id",{companyId:e,slotId:n});try{await Jl(e,t,n)}catch(i){Tt.error("failed to release slot",{companyId:e,err:i})}}async function Fv(s,e){let t=Object.values(ms).filter(Boolean);if(t.length!==0)try{await Yl(s,e,t)}catch(r){Tt.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}function Uv(s,e){Wf=global.setInterval(()=>Fv(s,e),1e4)}async function Bv(s,e){let t=Object.keys(ms);if(t.length){Tt.warn("not all slots released before end runner flow",{companyId:s});try{await se(t,r=>zl(Number(r),s,e))}catch(r){Tt.error("failed to release all slots",{err:r,companyId:s})}}}async function jv(s,e){await Bv(s,e),clearInterval(Wf)}async function Gf(s,e,t){let r;try{r=await Kl(s,e)}catch(n){throw Tt.error("failed to get slot",{companyId:s,err:n}),new Error(yt.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(yt.UNKNOWN);if(r.status==="success")return Vf(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new st(yt.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 st(yt.UNKNOWN))}async function Hf(s,e,t,r){let n=ms[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Vf(r,n),await Xl(s,e,n),Tt.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var Tt,ms,Wf,Vf,xn,fs=E(()=>{"use strict";ge();$();B();ae();Y();Tt=P("slot-service"),ms={},Wf=null,Vf=(s,e)=>{ms[s]=e};xn={start:Uv,end:jv}});function zf(s,e=process){async function t(r){await le(se(qf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Cn.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(Cn.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Cn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Cn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Cn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function gs(s){qf.push(s)}var Cn,qf,Pn=E(()=>{"use strict";$();B();Cn=P("process-handler"),qf=[]});var Yf={};z(Yf,{installAllLazyDependencies:()=>Gv,lazyRequire:()=>ut});async function ut(s,e={}){let t=rl(s);if(t)return t;let r;e.silent||(r=(0,Kf.default)(`Installing ${s} before first usage...`).start());try{let n=await Vv(s);return r&&r.succeed(),n}catch(n){Wv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Xf(s),o=`${s}@${i}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${o}`;throw r&&r.fail(l),n}}async function Vv(s){return hs.has(s)||(hs.set(s,Jf(s)),hs.get(s).catch(()=>{hs.delete(s)})),hs.get(s)}async function Jf(s){let e=rl(s);if(e)return e;let t=Xf(s),r=`${s}@${t}`;return await qi(ht(),r),tr(s)}async function Gv(){let s=Object.keys(hc);for(let e of s)await Jf(e)}function Xf(s){let e=Object.entries(hc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Kf,Wv,hs,kn=E(()=>{"use strict";Kf=I(require("ora"));os();$();B();bi();an();Wv=P("lazy-require"),hs=new Map});var Qf,yo,Zf=E(()=>{"use strict";Qf=require("istanbul-lib-report"),yo=class extends Qf.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 eg,tg,rg,On,wt,sg,bo,Ql,ng,Hv,ig,og,qv,zv,ag,Kv,Jv,Xv,Yv,Qv,cg,lg=E(()=>{"use strict";eg=I(require("ora")),tg=I(require("dayjs")),rg=I(require("test-exclude")),On=I(require("fs")),wt=I(require("path")),sg=I(require("istanbul-reports")),bo=I(require("istanbul-lib-report"));ge();Y();B();$();kn();Zf();Ql=P("test-run-status"),ng=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Hv=s=>!!ng(s).search,ig=s=>s?ng(s).pathname.substring(1):"",og=(s,e)=>{let t=ig(e);return!new rg.default({relativePath:!1,include:s}).shouldInstrument(t)},qv=s=>s.substring(0,s.indexOf("?")),zv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await ut("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},ag=(s,e)=>`${wt.resolve(s,ig(e))}.js`,Kv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await se(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await se(i.sources,async(o,a)=>{if(og(r,o))return;let c=ag(e,o);await On.promises.mkdir(wt.parse(c).dir,{recursive:!0}),await On.promises.writeFile(c,i.sourcesContent[a])})})},Jv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Hv(e)&&(e=qv(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)}},Xv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=bo.createContext({dir:t,coverageMap:e,watermarks:bo.getDefaultWatermarks(),sourceFinder:a=>{try{let c=ag(r,a);return On.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new yo({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Jv}),sg.create(a,c).execute(o)}),i},Yv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await ut("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>og(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},Qv=async(s,e)=>{let{mergeProcessCovs:r}=await ut("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await eu(s,"testResult",`runId=${e}`)).data.docs;return await se(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await _n(c,9e4);await se(l,async m=>{if(!i.has(m.url)){let d=m.text;m.sourceUrl&&(i.set(m.url,"TEMP"),d=await Zl(m.sourceUrl)),i.set(m.url,{text:d,url:m.url,sourceMapType:m.sourceMapType,hash:m.hash})}delete m.text,n=r([n,{result:[m]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},cg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Ql.info("start js coverage process");let n=(0,eg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=wt.resolve(s.codeCoverageReportPath||"./coverage"),o=wt.resolve(i,`.js/${(0,tg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?wt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:m}]=await Promise.all([ut("istanbul-lib-coverage"),Qv(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Ql.info("start js coverage merge and remap",{numOfFiles:m.size,numMergedCoverages:l.result.length});let d=c.createCoverageMap({}),u={};await se(l.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=m.get(h),v=await zv({sourceMapType:T,source:y,sourceMapDir:a});u[h]=v;let b=await Yv(s,{source:y,sourceMap:v,functions:g});d.merge(b)}),await Kv(s,o,u);let f=await Xv(s,d,i,o);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof C?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),Ql.error(l,{err:c})}}});var ug={};z(ug,{SELENIUM_PERF_MARKS:()=>Pe,SeleniumPerfStats:()=>xr});var Pe,Zv,xr,ys=E(()=>{"use strict";B();Pe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Zv=["ALL",...Object.values(Pe)],xr=class{constructor(){this.marks=Object.fromEntries(Zv.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=re();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`,Mi(r,50)],[`${t}_P95`,Mi(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var fg={};z(fg,{initServer:()=>rS,mapFilesToLocalDrive:()=>ru});function ru(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,To[t.id]?{screenshot:To[t.id]}:{})),Object.keys(wo).forEach(t=>{s.assets||={},s.assets[mg[t]]=wo[t]}),s.assets||={},s.assets.screenshots=Object.values(To)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function rS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await ut("multer"),n=typeof t=="string"?t:eS;await tu.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(c,l,m){let d=JSON.parse(c.body.metadata||"{}");if(!d.testResultId)return m(new Error("missing testResultId"),"");let u=Ln.join(n,d.testResultId);try{await tu.promises.mkdir(u,{recursive:!0})}catch(f){return m(f,"")}return m(null,u)},filename(c,l,m){let{fileName:d}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!d)return m(new Error("missing stepId or fileName"),"");if(u.stepId){let f=Ln.extname(d);return m(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return m(null,d)}})}),o=(0,dg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(c,l)=>{let m=JSON.parse(c.body.metadata||"{}");m.stepId&&(To[m.stepId]=c.file.path),m.testResultId&&tS.includes(m.subType)&&(wo[m.subType]||=[],wo[m.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 m=a(o);m.listen(s,e),m.on("error",d),m.on("listening",()=>c(m.address()));function d(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new C(`Port ${s} is already in use`));default:return l(u)}}})}var tu,pg,Ln,dg,eS,To,wo,mg,tS,su=E(()=>{"use strict";tu=I(require("fs")),pg=I(require("os")),Ln=I(require("path")),dg=I(require("express"));Y();kn();eS=Ln.join(pg.tmpdir(),"testim/rca/"),To={},wo={},mg={"test-log":"consoleLogs","har-file":"networkLogs"},tS=Object.keys(mg)});var nr,nu,vo,gg=E(()=>{"use strict";nr=I(require("lodash"));B();$();nu=P("override-test-data-builder"),vo=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):nu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):nu.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}nu.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 nr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(m=>this.generateTestUniqId(m)),o=i.indexOf(n),a=i.lastIndexOf(n),c=r[o],l=this.createNewTestItems(c,t);return r.splice(o,a-o+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=re();return{...e,resultId:i,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function So(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Ar,Qe,sS,nS,iS,oS,Eo,hg=E(()=>{"use strict";Ar=I(require("lodash"));B();ae();cs();fs();ge();Y();$();Lt();Pn();lg();ys();su();oe();de();gg();In();Qe=P("test-run-status"),sS=Tr(),nS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,iS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,oS=rt();Eo=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new xr;var a,c,l,m;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=Zs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:vi||t.parallel||1,browser:i,gitBranch:sS,gitCommit:nS,gitRepoUrl:iS,runnerVersion:oS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(d=>d.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:(m=t.gridData)==null?void 0:m.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:m,testStatus:d,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:v}=a,b={originalTestResultId:t,previousTestResultId:r,config:Ar.cloneDeep(c),testId:l,status:"QUEUED",name:m,resultId:e,retryCount:o,testStatus:d};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:v},au({projectId:n,runId:i,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,Q.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var l;let{project:n,remoteRunId:i,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Ro(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(m){Qe.error("failed to upload test data artifact (runner)",{err:m})}let c=Ar.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,Cr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await So(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...i},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(i){throw Qe.error("Failed to start test",{err:i}),i}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Qe.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Xe.EVALUATING&&_t.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Xe.EVALUATING} status`);return}if(l){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,ze(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,n,c)}calcResultText(e){return e.success?fe.PASSED:fe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Xe.QUARANTINE}`)}monitorMemoryUsage(e){let t=Kc();t.isOverThreshold&&Qe.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&ru(o,Qe),o.resultUrl=ze(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Q.onTestFinished(o,e,i);let c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await So(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){Qe.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 Cr(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Qe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=$c;return e&&(n=i),Qr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g;let c=e.browser?rn(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=Zr(O,n)&&tn(a.nativeApp)&&!e.appId,m=Zt(e)&&(Qr(a.nativeApp,n)||l),d=Ye(a,e)||m,u={testId:a.testId,testOptimization:a.testOptimization,status:d?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,...m&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:c.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await xn.end(r,t),e==="mongo"&&await Tn.end(t)}async executionStart(e,t,r,n,i){Qe.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:m}=o;gs(()=>Promise.all([this.endKeepAlive(m,t,l),Io("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let d={projectId:t,executionId:e,...O.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await So(o.beforeSuite,d),f=new vo(u,Ar.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let v=async()=>{let b=Ar.cloneDeep(this.testRunStatus);await se(Object.keys(b),async A=>{var L;let D=b[A],V=(L=D.config)==null?void 0:L.testData,x=D.testId,R=await Ro(t,x,A,V,c.defaults);R&&(delete D.config.testData,D.config.testDataUrl=R)});let w=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),S=ou({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:w,intersections:o.intersections});return this.executionStartedPromise=S,S.catch(A=>Qe.error(A)),S};try{await v()}catch(b){Qe.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Ar.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 m;let t=Xc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:d,testStatus:u}of t)d===fe.PASSED&&n++,d===fe.SKIPPED&&i++,d===fe.FAILED&&u===Xe.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await So(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(d){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Qe.warn("error while running afterSuite Hook",{err:d,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await cg(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((m=this.options.lightweightMode)!=null&&m.onlyTestIdsNoSuite))try{return await Io("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(d){throw Qe.error("Failed to update suite finished",{err:d}),d}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await iu(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function cu(s){var i;let e=s.canary?"-master.zip":".zip",t=`${mt}/testim-headless${e}`,r=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(i=s.company)==null?void 0:i.companyId,projectId:s.project,runnerEnvironment:xt});return r||(aS.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),r=`${mt}/testim-headless.zip`),!(s.ext||s.extensionPath)&&r&&(t=r,s.testimHeadlessExtensionDownloadUrl=r),{chrome:t,"edge-chromium":t}}function yg(s){let{chrome:e}=cu(s);return e}function xo(s){let e=xt==="staging"?`${mt}/staging-sessionPlayer`:`${mt}/sessionPlayer`;return s.canary?`${e}-master`:e}var aS,Dn=E(()=>{"use strict";oe();de();$();aS=P("runOptionsUtils")});function bs(s){var n;let t=(n=new RegExp(`^\\b(${Object.values(lu).join("|")})`).exec(s))==null?void 0:n[0];return t||lu[Ed]||"usw2"}var lu,Tg,Ao=E(()=>{"use strict";oe();lu={"us-west-2":"usw2","eu-central-1":"euc1"},Tg=Object.fromEntries(Object.entries(lu).map(([s,e])=>[e,s]))});function wg(s,e){if(e){if(!mS.has(e)){Nn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var vg,Sg,Gt,Eg,Ig,Rg,Co,xg,Nn,cS,lS,Mn,uS,pS,dS,ne,mS,Po=E(()=>{"use strict";vg=I(require("ms")),Sg=I(require("p-retry")),Gt=I(require("node:os")),Eg=I(require("portfinder")),Ig=I(require("node:child_process"));B();Ge();ge();Rg=I(require("node:fs")),Co=I(require("node:fs/promises")),xg=require("node:path");Y();$();Dn();ae();de();B();Ao();Nn=P("lambdatestService"),cS="https://downloads.lambdatest.com/tunnel/v3",lS={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"},Mn=`${Gt.tmpdir()}/LT`,uS=`${Mn}/LT`,pS=(0,vg.default)("15m"),dS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===_.TESTIM_LAMBDATEST||e.type===_.LAMBDATEST||e.type===_.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t,r){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=uu(t,r),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?pS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(uS))return;let t=lS[Gt.platform()+Gt.arch()];if(!t)throw new Error(`tunnel on ${Gt.platform()+Gt.arch()} platform is not supported.`);let r=`${Mn}.zip`;await Je(`${cS}/${t}`,r),await ot(r,Mn)}static async chmodLtTunnel(e){if(!(Gt.platform()==="win32"||!await ye(e))){try{await Co.access(e,Rg.constants.X_OK);return}catch{}try{await Co.chmod(e,"777")}catch(r){throw Nn.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 Eg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;ne.tunnelName=re();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,...Hc(u)])}if(O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)l=[...l,"--user",n,"--key",i];else throw new C("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 C("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await ne.delay(3e3),await ne.chmodLtTunnel((0,xg.join)(Mn,"LT")),ne.tunnel=Ig.spawn("./LT",l,{cwd:Mn});let m="",d="";ne.tunnel.stdout.on("data",u=>{m+=u.toString()}),ne.tunnel.stderr.on("data",u=>{d+=u.toString()});try{let u=await(0,Sg.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(m.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Nn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:m,stderrResult:d}),Nn.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",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,c){var S,A;if(!this.isActive)return{};let l=ne.lambdatestConfig.CAPABILITIES[t]||{},m={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},d=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:wg(n,a==null?void 0:a.os)||wg(n,(S=o==null?void 0:o.lt)==null?void 0:S.platform)||l.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??dS,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 D=cu({canary:u});!h&&D[t]&&(d=[...d,D[t]]),h&&De(h)&&(d=[...d,h]),d.length||Nn.warn("No extension was loaded in LambdaTestService",{extUrls:D,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&De(g)&&(d=[...d,g]);let T=bs(e.project||""),b={euc1:"eu"}[T],w=b?{region:b}:{};return{build:r,name:`${n} - ${i}`,...w,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.lambdatestConfig.TIMEZONE,...l,...y,loadExtension:d,...m,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},mS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey","macOS Catalina","macOS Big Sur"])});function gS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Dg(s){return kg.readFileSync(s,{encoding:"base64"})}function Ng(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&De(s))&&s){let r=Dg(s);ws.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${mu(r)} current extension count: ${e.length}`),e.push(r)}}function Mg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let m=typeof s.ext=="string"?s.ext:`${__dirname}/..`,d=r||m,u=`--load-extension=${d}`;ws.info(`adding extension: testim unpacked , path: ${d}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=ko.basename(i));let c=ko.join(process.cwd(),a),l=Dg(c);ws.info(`adding extension: testim zipped, path: ${c} length: ${l.length} hash: ${mu(l)} current extension count: ${e.length}`),e.push(l)}function hS(s,e,t,r,n,i,o,a){var g,y;let c=t.seleniumName||t.browserValue,l=[],m=[...Lg];e.headless&&m.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":pu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":pu.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(du(n)){let T=O.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&m.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}du(n)&&c==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>m.push(`--${T}`));try{let T=Oo();T.length&&T.forEach(v=>m.push(`--disable-features=${v}`))}catch{}e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=pu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&m.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&m.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:c});function u(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Bc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),Ng(r,l,o),a===K.EXTENSION&&Mg(e,l,m,i,o),l.length>0&&(d.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=m;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[c],h={MicrosoftEdge:"ms",chrome:"goog"}[c];return ne.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=d),s}function bS(s,e,t){let r={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Cg.join(","),"browser.helperApps.neverAsk.openFile":Cg.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 Ts(s){return`${s.width}x${s.height}`}function IS(s){let{platform:e}=s;if(!e)return Ts(Pg);let t=e.split(" ")[1];return e.startsWith("Windows")&&ES.has(t)?Ts(wS):e==="Linux"?Ts(TS):e.startsWith("macOS")?Ts(vS):Ts(e==="OS X El Capitan"||e==="OS X Yosemite"?SS:Pg)}function RS(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(n["sauce:options"].screenResolution=IS(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let i=(0,_g.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,pt.merge(i,n,r)}return pt.merge(n,r)}return{}}function xS(s){let{runnerOptions:e}=s;if(pt.isEmpty(e.browserstack))return{};let{projectData:t,testRunConfig:r,testId:n,testName:i,executionId:o,executionName:a}=s,c={buildName:`${a} - ${o}`,sessionName:`${i} - ${n}`,projectName:`${t.name} - ${t.projectId}`,...e.browserstack};return r&&r.browserValue==="safari"&&r.bs.safari_version&&(c.os_version=r.bs.safari_version,r.bs.safari_version==="10"&&Object.assign(c,{"safari.options":{technologyPreview:!0}})),c}function AS(s){return s.perfecto?s.perfecto:{}}function CS(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 PS(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,i=r||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=mc(i,o)),a}function Oo(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function _o(s){var A,D,V,x;let{overrideConfiguration:e,browserOptions:t,testId:r,testName:n,testRunConfig:i,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:m,testResultId:d,lambdatestService:u,mode:f}=s;if(o.mode==="local"){let R=[],L=[...Lg],M={};t.headless&&L.push("--headless"),t.silentDebuggerExtensionApi&&L.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&L.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let G=Oo();G.length&&G.forEach(W=>L.push(`--disable-features=${W}`))}catch{}return t.chromeExtraArgs&&t.chromeExtraArgs.forEach(G=>L.push(`--${G}`)),t.chromeBinaryLocation&&(M.binary=t.chromeBinaryLocation),f!==K.SELENIUM&&Mg(t,R,L,null,u),Ng(a,R,u),{logLevel:Ag,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:L,extensions:R,...M},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:h,driverRequestRetries:g}=t,y=PS(t,o),T={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Ag,connectionRetryTimeout:h,connectionRetryCount:g,getSessionTimeout:Math.max(u.getSessionTimeout,t.getSessionTimeout),getSessionRetries:u.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!pt.isEmpty(y)&&{headers:y},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};du(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,T.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(T.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let v=Number(t.browserTimeout/1e3),b=t.browser||(i==null?void 0:i.browserValue),w={runnerOptions:t,testId:r,testName:n,testRunConfig:i,executionId:c,executionName:l,projectData:m};pt.merge(T.desiredCapabilities,RS(t,n,i),xS(w),AS(t),CS(t,b,v),u==null?void 0:u.getCapabilities(t,b,c,d,n,i,e,f));let S=null;switch(!t.ext&&!t.extensionPath&&((A=o.host)!=null&&A.endsWith(".testim.io"))&&!t.canary&&f===K.EXTENSION&&(b==="chrome"||b==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(S="/opt/testim-headless"),b){case"chrome":case"edge-chromium":T=yS(T,t,i,a,o,S,u,f);break;case"firefox":T=bS(T,t,u);break;case"safari":case"safari technology preview":T=gS(T,b);break;default:break}pt.merge(T.desiredCapabilities,t.seleniumCapsFileContent);try{let R={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},L=q=>q[o.provider]||q[T.host]||q[R[T.host]],M=q=>{var ie,Ie;return L(q)||q[(ie=T.desiredCapabilities)==null?void 0:ie.browserName]||q[(Ie=T.desiredCapabilities)==null?void 0:Ie.version]||q||{}},G=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),W=M(M(G));Object.keys(W).length&&(ws.info(`Adding custom capabilities: ${JSON.stringify(W)}`),Object.assign(T.desiredCapabilities,W))}catch(R){ws.error("Failed to load custom capabilities",{error:R,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(T.desiredCapabilities&&!T.capabilities&&(fS(T),T.capabilities={alwaysMatch:T.desiredCapabilities,firstMatch:[{}]},delete T.desiredCapabilities),T.hostname=T.host,s.printFinalCaps){let R=(D=T.capabilities)==null?void 0:D.alwaysMatch,L=JSON.parse(JSON.stringify(T)),M=(V=L==null?void 0:L.capabilities)==null?void 0:V.alwaysMatch,G=q=>q.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(q=>{var ie,Ie;M!=null&&M[q]&&(M[q].extensions=(Ie=(ie=R==null?void 0:R[q])==null?void 0:ie.extensions)==null?void 0:Ie.map(G))}),M!=null&&M.loadExtension&&(M.loadExtension=(x=R==null?void 0:R.loadExtension)==null?void 0:x.map(G));let W=require("node:util");console.log(W.inspect(L,{showHidden:!1,depth:null,colors:!0}))}return T}var kg,ko,Og,pt,_g,ws,Ag,pu,Lg,mu,du,fS,yS,Cg,Pg,TS,wS,vS,SS,ES,Lo=E(()=>{"use strict";kg=I(require("node:fs")),ko=I(require("node:path")),Og=I(require("node:crypto")),pt=I(require("lodash"));B();oe();$();de();ae();Po();_g=require("lodash"),ws=P("testim-desired-capabilities-builder"),Ag=wi?"debug":"silent",pu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Lg=["--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"],mu=(...s)=>Og.createHash("sha256").update(s.join("")).digest("hex"),du=s=>s.type===_.DEVICE_FARM||s.type===_.HYBRID&&s.provider==="devicefarm",fS=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=O.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ws.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};yS=pt.memoize(hS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(pt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return mu(o,a,c,r,l,i)}),Cg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Pg={width:1920,height:1080},TS={width:1920,height:1200},wS={width:2560,height:1600},vS={width:2360,height:1770},SS={width:2048,height:1536},ES=new Set(["7","8","8.1","10","11"])});function Ue(s){var e,t,r,n,i,o,a,c;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||((t=s.message)==null?void 0:t.toLowerCase())==="unknown error"||((r=s.message)==null?void 0:r.match(/Unknown timeout type/))||s.name==="unknown command"||((n=s.message)==null?void 0:n.match(/did not match a known command/))||((i=s.message)==null?void 0:i.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=s.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((c=s.message)==null?void 0:c.match(/\.\w* is not a function/))}function Ug(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 fu=E(()=>{"use strict"});function gu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function i(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return i(y,f)}function o(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=i(u,"stroke-width");return!!g&&parseInt(g,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(u){return i(u,"overflow")==="hidden"}function c(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:c(f))}function l(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:l(u.parentNode):!1}if(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return gu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let m=!!n(s,u=>Number(i(u,"opacity"))===0),d=!!n(s,u=>i(u,"display")==="none");return!(m||d||!o(s)||c(s))}var Bg=E(()=>{"use strict"});var jg,$g,Ht,kS,OS,Do,Wg=E(()=>{"use strict";jg=I(require("promise-queue")),$g=I(require("webdriverio"));oe();$e();B();$();Hr();Bg();fu();ys();Ht=P("WebDriverApi"),kS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},OS={implicit:0,pageLoad:1,script:2},Do=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,i=t?t.toString().slice(0,2e3):"";throw Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),yc!==void 0&&(e=yc);let t=1/0;this.queue=new jg.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,a,c,l,m,d,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),F("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((d=(m=(l=(c=e.capabilities.alwaysMatch)==null?void 0:c["goog:chromeOptions"])==null?void 0:l.extensions)==null?void 0:m[0])==null?void 0:d.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(Pe.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),F("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await $g.remote(e),this.logGridStatus(r)}),F("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,Pe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){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:i.message,ready:i.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){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(Ue(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Ue(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Pe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,Pe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Pe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Ne(e)))}finally{this.seleniumPerfStats.markEnd(t,Pe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(gu,{ELEMENT:e,[Jt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ue(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Ug(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 i=[];return i[OS[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(Ue(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Ne(e)),await this.elementIdValue(Ne(e),t)}async getViewportSize(e){let t=await this.execute(kS);if(typeof e=="string"&&/(width|height)/.test(e)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Ne(e))})}submitFormManually(e){return this.addToQueue(async()=>{var i;let t=await((i=this.client)==null?void 0:i.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let i=await this.client.$(e);await this.client.action("pointer").move({origin:i}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,o),n=async()=>await this.client._setWindowSize(i,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(i){if(Ue(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){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 ir={};z(ir,{getSessionPlayer:()=>Z,options:()=>yu});var No,yu,hu,Z,we=E(()=>{"use strict";No=require("path");$();yu={playerPath:void 0},Z=()=>{if(hu)return hu;let s=($e(),qe(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(pn(),qe(un)),t=e(),r=yu.playerPath?(0,No.resolve)(yu.playerPath,"src/background/sessionPlayerInit.ts"):(0,No.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),hu=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(zd),n}});var Vg={};z(Vg,{doubleClick:()=>_S});var _S,Gg=E(()=>{"use strict";_S=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function f(v,b,w){return w>v&&w<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},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},m=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},d=function(u){let f=o(u),h=u.event;return t.includes(h)?c(h,f.x,f.y):l(h,f.x,f.y)};try{n.map(f=>d(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=m();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Fn={};z(Fn,{dispatchFocus:()=>LS});function LS(s,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function r(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let i=getLocatedElement(s);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Un=E(()=>{"use strict"});var Jg={};z(Jg,{WebDriver:()=>Or});async function FS(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 NS(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var vs,zg,Kg,Be,or,DS,Hg,NS,Pr,MS,qg,kr,Or,Bn=E(()=>{"use strict";vs=I(require("lodash"));B();$e();Lo();zg=I(require("p-retry")),Kg=I(require("ua-parser-js"));Hr();$();fu();Wg();Y();de();ys();Be=P("webdriver"),[or,DS]=[0,2],{extractElementId:Hg,getCdpAddressForHost:NS}=X,Pr=()=>(we(),qe(ir)).getSessionPlayer().codeSnippets,MS=()=>(we(),qe(ir)).getSessionPlayer().locatorBuilderUtils,qg=()=>(we(),qe(ir)).getSessionPlayer().utils,kr=()=>(we(),qe(ir)).getSessionPlayer().positionUtils;Or=class extends Do{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 A,D,V,x,R,L,M,G;let{projectData:r,overrideConfiguration:n,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:m,executionId:d,executionName:u,testResultId:f,seleniumPerfStats:h,fastInit:g,lambdatestService:y,printFinalCaps:T,mode:v}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((V=(D=(A=i==null?void 0:i.company)==null?void 0:A.activePlan)==null?void 0:D.premiumFeatures)==null?void 0:V.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let b=_o({projectData:r,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:m,executionId:d,executionName:u,testResultId:f,lambdatestService:y,overrideConfiguration:n,printFinalCaps:T,mode:v});b.desiredCapabilities&&delete b.desiredCapabilities.marionette,b.capabilities&&delete b.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(y==null?void 0:y.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=h;let w=g?0:1500,S=g?()=>null:()=>this.executeJS("window.focus()");try{F("before initClient in webdriver.js init");let W=await this.initClient(b,a,f);F("after initResult before getCdpAddress in init"),this.cdpUrl=await FS(W),F("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await pe(w),O.flags.dontFocusOnInit.isEnabled()||await S(),F("after focus and delay in webdriver.js init")}catch(W){let q=JSON.stringify(vs.omit(b,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:W,capabilitiesAsString:q});let ie=((R=(x=i==null?void 0:i.company)==null?void 0:x.activePlan)==null?void 0:R.plan)==="free";throw(L=W.stack)!=null&&L.includes("at startWebDriverSession")&&((M=W.message)!=null&&M.startsWith("Failed to create session"))&&((G=W.message)!=null&&G.includes("Timeout awaiting 'request'"))&&ie?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(W.message)?new zr(W.message):/capabilit(y|ies)/.test(W.message)?new Ri(W.message):/403 Forbidden/.test(W.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(W.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${W.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>vs.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,c)=>{let l=this._keepAliveRequests.find(m=>m.id===c);l&&(l[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=re();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,Be.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Be.warn("failed to click on alert",{err:c}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.handleThresholdBasedError(this.browserClosedCallbacks,a)}else this.generalKeepAliveFailures++,this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures>=3&&this.handleThresholdBasedError(this.keepAliveFailedCallbacks,a)}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}handleThresholdBasedError(t,r){t.forEach(n=>{try{n(r)}catch{}})}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Hg(r.value);return await this.switchToFrame({ELEMENT:n,[Jt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new xi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(Pe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Pe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
19
- var fn = ${Pr().getLocatedElementCode};
17
+ 4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),o}}async function iv(){let s=At==="staging"?`${ft}/Staging-LATEST_VERSION`:`${ft}/sessionPlayer_LATEST_RELEASE`;return(await Wt(s)).body.toString("utf8")}function ov(){return`${ft}/dev-sessionPlayer.zip`}async function av(s,e){if(!De(s)||De(s)&&e||We)return s;let t=await iv();return`${s}-${t}${At==="staging"?".zip":""}`}function ml(){let s=yt();return as.resolve(s,"testim-bin")}function cv(){let s=ml();return as.resolve(s,"sessionPlayer.zip")}async function af(s,e,t=!1){try{return await Oi(s,e),await ot(e,ml())}catch(r){if(t)throw r;return await af(s,e,!0)}}async function Er(s,e){Xi.info("prepare player",{location:s,canary:e});let t=cv();return Ot(async()=>{let r=At==="development"?ov():await av(s,e);return await af(r,t),{}},"preparePlayer",of,[s,e,t])()}var rf,sf,as,nf,Xi,of,ul,tf,dn=S(()=>{"use strict";rf=I(require("ms")),sf=I(require("node:fs")),as=I(require("node:path"));oe();er();nf=require("serialize-error");W();rl();Y();B();Xi=P("prepare runner and testim start"),of=(0,rf.default)("0.5 day"),ul=16,tf=`The size of the custom extension is more than ${ul}MB`});function lv(){let s=mn.type().toLowerCase();return s==="darwin"?mn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?mn.arch()==="x64"?"win64":"win32":"linux"}async function Qi(){let s=lv(),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 C(`Unsupported platform: ${s}`);let r=parseInt(fn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},i={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},o=`${e}/${t[s]}/${fn}/${n[s]}.zip`,a=Yi.join(fl,n[s]),c=`${a}.zip`,l=Yi.join(a,i[s]);if(await ye(l))return l;if(!await ye(c)){let d=(0,gl.default)("Downloading Chromium").start();try{await cf.promises.mkdir(fl),await Je(o,c)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw d.fail(f),new Error(f)}d.succeed()}let m=(0,gl.default)("Extracting Chromium").start();try{await ot(c,fl)}catch(d){let u=`Failed to extract Chromium: ${d.message}`;throw m.fail(u),new Error(u)}return m.succeed(),l}var cf,mn,Yi,gl,fn,fl,hl=S(()=>{"use strict";cf=I(require("fs")),mn=I(require("os")),Yi=I(require("path")),gl=I(require("ora"));Y();B();fn="1000968",fl=Yi.join(Gt,`chrome-${fn}`)});async function pf(s,e){return Ir=s,wl=e,await yl()}function df(s,e){Ir=e.projectId,wl=e.token,gn=e.userAccessKey,at=s.token,yn=vl(at),bn=s.refreshToken,bl=s.ngrokToken,Tl=s.isNgrokWhitelisted,lf=e.publicIp,uf=e.initializedFromCache}function pv(s=Ir,e=wl){return Ot(()=>(hn.info("request to get cli token from server"),Ve({url:`${he()}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",uv*10,{projectId:s,token:e})()}async function dv(){hn.info("request to refresh JWT cli token from server");let s=await Ve({url:`${he()}/auth/refreshToken`,body:{token:at,refreshToken:bn}});return at=s.token,yn=vl(at),s.refreshToken&&(bn=s.refreshToken),at}async function yl(){try{let s=await pv();return hn.info("successfully get cli token from server"),at=s.token,yn=vl(at),bn=s.refreshToken,bl=s.ngrokToken,Tl=s.isNgrokWhitelisted,at}catch(s){throw s.message.includes("Unauthorized")?new C("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."):(hn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Ir}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function vl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function _t(){if(!yn)return yl();let s=O.flags.accessTokenExpiryMargin.getValue();if(yn<Date.now()+4*s)try{return await dv()}catch(e){return hn.error("failed to refresh token, executing fallback",e),yl()}return at}function Zi(){return bn}function Rr(){return at?{uid:require("jsonwebtoken").decode(at).id,ngrokToken:bl,isNgrokWhitelisted:Tl}:{}}async function eo(){if(!gn||!Ir)return;if(await Sl({userAccessKey:gn,projectId:Ir}))return gn;let e=`user access key "${gn}" is invalid for project "${Ir}"`;throw new C(e)}function to(){return lf}function ro(){return uf}var hn,at,yn,bn,bl,Tl,Ir,wl,gn,lf,uf,uv,ct=S(()=>{"use strict";oe();Ge();er();Y();W();ge();de();hn=P("testim-custom-token"),Ir=null,wl=null,uv=5*60*1e3});function mv(s){if(s.protocol)return s.protocol;if([_.TESTIM_PRIVATE,_.TESTIM,_.BROWSERSTACK,_.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([_.TESTIM_ENTERPRISE,_.TESTIM_LAMBDATEST,_.DEVICE_FARM].includes(s.type)){let e=mf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function fv(s){let e=mf.exec(s);return e==null?void 0:e[3]}function no(s){var v,E,A,D,V,x,R,L,M,H,j;let e=s&&fv(s.host),t=s.port,r=s.path,n=s&&mv(s),i=s.token,o=s.slotId,a=(v=s.hybrid)==null?void 0:v.tunnel,c=(E=s.external)==null?void 0:E.user,l=(A=s.external)==null?void 0:A.key,m=s.type,d=m===_.HYBRID?a&&((x=(V=(D=s.hybrid)==null?void 0:D.external)==null?void 0:V[s.hybrid.tunnel])==null?void 0:x.user):c,u=m===_.HYBRID?a&&((M=(L=(R=s.hybrid)==null?void 0:R.external)==null?void 0:L[s.hybrid.tunnel])==null?void 0:M.key):l,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(H=s.mobileTokens)==null?void 0:H.androidToken,T=(j=s.mobileTokens)==null?void 0:j.iosToken,w=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:c,key:l,type:m,name:f,provider:g,tunnelUser:d,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:w,isSupportGrid:b}}async function hv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(c){throw lt.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(bt.UNKNOWN)}if(lt.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw lt.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,yf(n));let c=no(o.grid);return gv(t,e,c.gridId,c.slotId,r,c.isSupportGrid),c}throw o.code==="not-found"?new st(bt.NOT_FOUND):o.code==="no-available-slot"?new Yt(`Failed to run test on ${r} - concurrency limit reached`):(lt.error("invalid code error response - get grid",{res:o}),new st(bt.UNKNOWN))}function gf(s){return Cl(s)}async function hf(s,e,t){let n=(t||await gf(s)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return no(n)}async function yv(s,e,t){let n=(t||await gf(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return no(n)}async function El(s,e){let t=Tn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete Tn[s],!a){if(!r){lt.warn("failed to find grid slot id",{projectId:e});return}lt.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await Rl(o,e,r,n,i)}catch(c){lt.error("failed to release slot",{projectId:e,err:c})}}}async function bv(s){let e=Object.values(Tn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid)try{await Il(s,e)}catch(t){lt.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}function Tv(s){ff=global.setInterval(bv,1e4,s)}async function wv(s){let e=Object.keys(Tn);if(e.length){lt.warn("not all slots released before end runner flow",{projectId:s});try{await se(e,t=>El(Number(t),s))}catch(t){lt.error("failed to release all slots",{err:t,projectId:s})}}}async function vv(s){await wv(s),clearInterval(ff)}function Sv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function Ev(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function yf(s){let t=(()=>so.isEmpty(s.testobjectSauce)?so.isEmpty(s.saucelabs)?so.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=Sv(t,s),c=Ev(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:c,key:a,gridId:re()}}async function bf(s,e){let t=s.company.companyId;return await hf(t,e.gridId,s.allGrids)}async function Tf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:c}=s;if(n||o||i)return{mode:"local"};if(r)return yf(s);let l=t==null?void 0:t.companyId;if(a)return hf(l,a,e);if(c)return yv(l,c,e);if(tn(s)||s.tunnelOnlyMode){lt.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new st("Missing host or grid configuration")}async function wf(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:c,localTmaUrl:l,useLocalChromeDriver:m,useChromeLauncher:d,company:u}=t,f=Boolean(m||d||l),h=u==null?void 0:u.companyId;return hv(o,h,r,s,t,()=>Al({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:i,testResultId:n}))}var so,lt,Tn,mf,ff,gv,wn,vf,cs=S(()=>{"use strict";so=I(require("lodash"));ge();W();B();ae();Y();lt=P("grid-service"),Tn={},mf=/(^(https?):\/{2})?(.*)/,ff=null;gv=(s,e,t,r,n,i)=>{Tn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};wn={start:Tv,end:vv};vf=async(s={},e={},t={},r={},n={})=>{var g,y,T;let{company:{companyId:i}={},project:o}=s,{gridId:a,type:c}=e,l=s.browser||t.browserValue,m=Boolean(s.tunnel),{maxRetries:d,currentRetry:u}=n;if(!a||!c||((c===_.TESTIM_LAMBDATEST||c===_.LAMBDATEST)&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e,i,o)),c!==_.HYBRID||!i||!l||!d||!u))return e;let f=await xl({companyId:i,gridId:a,maxRetries:d,currentRetry:u,browser:l,usingTunnel:m});lt.info("handling hybrid grid",{response:f,companyId:i});let h=no({...e,...f.connectionDetails,provider:f.provider});return f.provider!=="lambdatest"&&((y=r.disable)==null||y.call(r)),f.provider==="lambdatest"&&await((T=r.enableIfNeeded)==null?void 0:T.call(r,h,i,o)),h}});function Sn(){return io||"master"}function Sf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){io="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){io=s.branch||s;return}io=e?"master":void 0}var io,Pl=S(()=>{"use strict";Y()});function xf(s){We||(s!=null&&s.userId||(s={anonymousId:"runnerId"}),Rf.identify(s))}function Tt(s,e){return ls("ci",s,e)}function ls(s,e,t){if(We)return;let r=s?{userId:s}:{anonymousId:"runnerId"};Rf.track(Object.assign(r,{event:e,properties:t}))}var If,Rf,us=S(()=>{"use strict";oe();If=require("@segment/analytics-node"),Rf=new If.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1})});var Af={};z(Af,{isCi:()=>ps});var ps,oo=S(()=>{"use strict";ps=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Pf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function kf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:l,user:m,lightweightMode:d,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Pf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:Cf(l,m),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},d);Tt("test-run-ci",y)}function Of({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,source:m,user:d,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let w=Pf({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Cf(m,d),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){Tt("test-run-ci-success",w);return}Tt("test-run-ci-fail",{...w,failureReason:n.failureReason})}catch(w){f.error("failed to update test end analytics",{err:w})}}function _f(s){Tt("batch-run-ci",s)}var Cf,kl=S(()=>{"use strict";us();oo();Cf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ps&&e?"ci-with-user":ps?"ci":e?"cli-with-user":s});var Ol,ue,Df=S(()=>{"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 In,_l,Iv,Ll,Rv,ao,co,lo,uo,po,mo=S(()=>{"use strict";B();ae();In=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},Iv=s=>{let{status:e}=s;return e===fe.PASSED},Ll=s=>s.runnerStatus===$c.SKIPPED,Rv=s=>s.testStatus===Xe.EVALUATING,ao=(s,e)=>Object.values(s).filter(t=>{var r,n;return Ll(t)&&(Ye(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,co=s=>Object.values(s).filter(e=>In(e)&&Rv(e)).length,lo=s=>Object.values(s).filter(In),uo=s=>Object.values(s).filter(Iv),po=s=>Object.values(s).filter(_l)});function Av(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Dl,fo,xv,go,Nf=S(()=>{"use strict";Dl=I(require("lodash"));W();mo();fo=P("debug-reporter"),xv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],go=class{constructor(e){this.options=e}onTestStarted(e,t){fo.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;fo.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:c,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Dl.default.omit(this.options,xv),company:Dl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let c=Av(process.argv);fo.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,i){let o=uo(e).length,a=Object.keys(e).length-o;fo.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Nl,Lt,Rn=S(()=>{"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===_.DEVICE_FARM}},Lt=new Nl});var Fl={};z(Fl,{Reporter:()=>Cv});var sr,xn,xr,ho,Mf,Ml,Cv,Ul=S(()=>{"use strict";sr=I(require("chalk")),xn=I(require("lodash"));B();ae();Rn();mo();xr={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:ho}=Vt,Mf="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})`,n=`url: ${sr.default.underline(ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?fe.PASSED:fe.FAILED,n=`(${e.testId})`,i=xr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Di(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=ze(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(xr.error("Failed runs are:")),console.log(xr.error(t.join(`
18
+ \r`)))}onTestPlanFinished(e,t,r,n,i){let o=lo(e),a=uo(e),c=po(e),l=a.length,m=c.length,d=o.length,u="",f="";if(Lt.isTestStatusEnabled){let w=co(e);u=` FAILED-EVALUATING: ${w}`,d-=w,f=` SKIPPED: ${ao(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=xr[d?"error":"success"],T=`PASSED: ${l} FAILED: ${d}${u} ABORTED: ${m}${f} Duration: ${Di(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=xn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=xn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=xn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=xn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let c=u=>{u.forEach((f,h)=>{var w;let g=(w=f.testData)!=null&&w.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`,T="";f.testOptimization?T=` [${f.testOptimization.reason}]`:Ye(f,this.options)&&(T="-quarantine"),console.log(" ",h+1,":",`${f.name}${T}`,y,g)})},l=a?`config '${a}'`:"default configs",m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",d=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${d} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===ho.APPIUM?Mf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===ho.APPIUM?Mf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} 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 n=this.options.grid||this.options.gridId,i=this.options.mode===ho.APPIUM?"device":"browser";if(n)console.log(xr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(xr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===ho.APPIUM?"Appium":"Selenium";console.log(xr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},Cv=Ml});var $l={};z($l,{Reporter:()=>Dv});function Pv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function kv(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 Ov(s){return`${s.visitedUrlsJson||""}`}async function _v(s,e,t,r,n,i){function o(u){let f=ze(s,t,u.testId,u.resultId,r),h={$:{name:Pv(u),classname:n,time:Jc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(In(u)||_l(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=In(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Ll(u)&&Ye(u,i)&&Lt.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=kv(u),h["visited-urls-json"]=Ov(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},w={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(y),failures:m(y),timestamp:c(e)};if(Lt.isTestStatusEnabled){w.skipped=ao(y,i);let b=co(y);w.failures-=b,w["failure-evaluating"]=b}return{$:w,testcase:Object.keys(y).map(b=>o(y[b]))}}function c(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function l(u){return Object.keys(u).length}function m(u){return lo(u).length+po(u).length}let d={testsuites:{testsuite:e.map(u=>a(u))}};try{return new jl.Builder().buildObject(d)}catch(u){return Lv(u)}}function Lv(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,Ff,Bl,Dv,Wl=S(()=>{"use strict";jl=I(require("xml2js"));B();Ff=require("fs");Rn();mo();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,n=await _v(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Ff.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};Dv=Bl});var Uf={};z(Uf,{Reporter:()=>Nv});function ds(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,Nv,Bf=S(()=>{"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`:"",n=`${e.name} (${e.testId})${r}`;return ds(n)}onTestStarted(e,t,r,n){if(r){Vl.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,i,o){if(i){Vl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ds(t)}' details='${ds(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Vl.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ds(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ds(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ds(t)}']`)}},Nv=Gl});var jf={};z(jf,{Reporter:()=>Mv});var Hl,Mv,$f=S(()=>{"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,n,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},Mv=Hl});function bo(s){let{platform:e}=process;e==="win32"?(0,yo.exec)(`start chrome ${s}`):e==="darwin"?(0,yo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,yo.exec)(`google-chrome ${s}`)}var yo,ql=S(()=>{"use strict";yo=require("child_process")});var Wf={};z(Wf,{Reporter:()=>Fv});var zl,Fv,Vf=S(()=>{"use strict";B();ql();zl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return bo(t)}},Fv=zl});var Kl,Q,Dt=S(()=>{"use strict";Nf();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 go(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Ul(),Fl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Wl(),$l));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Bf(),Uf)),r.includes("console")&&Promise.resolve().then(()=>(Ul(),Fl)),r.includes("junit")&&Promise.resolve().then(()=>(Wl(),$l)),r.includes("json")&&Promise.resolve().then(()=>($f(),jf)),r.includes("chrome")&&Promise.resolve().then(()=>(Vf(),Wf))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,i){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var i;let n=t==null?void 0:t(...r);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||r))}}},Q=new Kl});async function Jl(s,e,t){let r=ms[s];if(!r)return;let{slotId:n}=r;if(delete ms[s],!n){wt.warn("failed to find slot slot id",{companyId:e,workerId:s});return}wt.info("release slot id",{companyId:e,slotId:n});try{await Yl(e,t,n)}catch(i){wt.error("failed to release slot",{companyId:e,err:i})}}async function Uv(s,e){let t=Object.values(ms).filter(Boolean);if(t.length!==0)try{await Zl(s,e,t)}catch(r){wt.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}function Bv(s,e){Gf=global.setInterval(()=>Uv(s,e),1e4)}async function jv(s,e){let t=Object.keys(ms);if(t.length){wt.warn("not all slots released before end runner flow",{companyId:s});try{await se(t,r=>Jl(Number(r),s,e))}catch(r){wt.error("failed to release all slots",{err:r,companyId:s})}}}async function $v(s,e){await jv(s,e),clearInterval(Gf)}async function qf(s,e,t){let r;try{r=await Xl(s,e)}catch(n){throw wt.error("failed to get slot",{companyId:s,err:n}),new Error(bt.UNKNOWN)}if(wt.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw wt.error("invalid response - get slot",{res:r}),new Error(bt.UNKNOWN);if(r.status==="success")return Hf(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new st(bt.NOT_FOUND):r.code==="no-available-slot"?new Yt("Failed to run test - concurrency limit reached"):(wt.error("invalid code error response - get slot",{res:r}),new st(bt.UNKNOWN))}async function zf(s,e,t,r){let n=ms[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Hf(r,n),await Ql(s,e,n),wt.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var wt,ms,Gf,Hf,An,fs=S(()=>{"use strict";ge();W();B();ae();Y();wt=P("slot-service"),ms={},Gf=null,Hf=(s,e)=>{ms[s]=e};An={start:Bv,end:$v}});function Jf(s,e=process){async function t(r){await le(se(Kf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Pn.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(Pn.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Pn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Pn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Pn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function gs(s){Kf.push(s)}var Pn,Kf,kn=S(()=>{"use strict";W();B();Pn=P("process-handler"),Kf=[]});var Zf={};z(Zf,{installAllLazyDependencies:()=>Hv,lazyRequire:()=>ut});async function ut(s,e={}){let t=nl(s);if(t)return t;let r;e.silent||(r=(0,Xf.default)(`Installing ${s} before first usage...`).start());try{let n=await Gv(s);return r&&r.succeed(),n}catch(n){Vv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Qf(s),o=`${s}@${i}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${o}`;throw r&&r.fail(l),n}}async function Gv(s){return hs.has(s)||(hs.set(s,Yf(s)),hs.get(s).catch(()=>{hs.delete(s)})),hs.get(s)}async function Yf(s){let e=nl(s);if(e)return e;let t=Qf(s),r=`${s}@${t}`;return await Ki(yt(),r),tr(s)}async function Hv(){let s=Object.keys(Tc);for(let e of s)await Yf(e)}function Qf(s){let e=Object.entries(Tc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Xf,Vv,hs,On=S(()=>{"use strict";Xf=I(require("ora"));os();W();B();Ti();cn();Vv=P("lazy-require"),hs=new Map});var eg,To,tg=S(()=>{"use strict";eg=require("istanbul-lib-report"),To=class extends eg.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var rg,sg,ng,_n,vt,ig,wo,eu,og,qv,ag,cg,zv,Kv,lg,Jv,Xv,Yv,Qv,Zv,ug,pg=S(()=>{"use strict";rg=I(require("ora")),sg=I(require("dayjs")),ng=I(require("test-exclude")),_n=I(require("fs")),vt=I(require("path")),ig=I(require("istanbul-reports")),wo=I(require("istanbul-lib-report"));ge();Y();B();W();On();tg();eu=P("test-run-status"),og=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},qv=s=>!!og(s).search,ag=s=>s?og(s).pathname.substring(1):"",cg=(s,e)=>{let t=ag(e);return!new ng.default({relativePath:!1,include:s}).shouldInstrument(t)},zv=s=>s.substring(0,s.indexOf("?")),Kv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await ut("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},lg=(s,e)=>`${vt.resolve(s,ag(e))}.js`,Jv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await se(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await se(i.sources,async(o,a)=>{if(cg(r,o))return;let c=lg(e,o);await _n.promises.mkdir(vt.parse(c).dir,{recursive:!0}),await _n.promises.writeFile(c,i.sourcesContent[a])})})},Xv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(qv(e)&&(e=zv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=vt.dirname(this.getPath(s));return vt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Yv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=wo.createContext({dir:t,coverageMap:e,watermarks:wo.getDefaultWatermarks(),sourceFinder:a=>{try{let c=lg(r,a);return _n.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new To({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Xv}),ig.create(a,c).execute(o)}),i},Qv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await ut("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>cg(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},Zv=async(s,e)=>{let{mergeProcessCovs:r}=await ut("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await ru(s,"testResult",`runId=${e}`)).data.docs;return await se(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Ln(c,9e4);await se(l,async m=>{if(!i.has(m.url)){let d=m.text;m.sourceUrl&&(i.set(m.url,"TEMP"),d=await tu(m.sourceUrl)),i.set(m.url,{text:d,url:m.url,sourceMapType:m.sourceMapType,hash:m.hash})}delete m.text,n=r([n,{result:[m]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},ug=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;eu.info("start js coverage process");let n=(0,rg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=vt.resolve(s.codeCoverageReportPath||"./coverage"),o=vt.resolve(i,`.js/${(0,sg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?vt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:m}]=await Promise.all([ut("istanbul-lib-coverage"),Zv(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}eu.info("start js coverage merge and remap",{numOfFiles:m.size,numMergedCoverages:l.result.length});let d=c.createCoverageMap({}),u={};await se(l.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=m.get(h),w=await Kv({sourceMapType:T,source:y,sourceMapDir:a});u[h]=w;let b=await Qv(s,{source:y,sourceMap:w,functions:g});d.merge(b)}),await Jv(s,o,u);let f=await Yv(s,d,i,o);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof C?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),eu.error(l,{err:c})}}});var dg={};z(dg,{SELENIUM_PERF_MARKS:()=>Pe,SeleniumPerfStats:()=>Ar});var Pe,eS,Ar,ys=S(()=>{"use strict";B();Pe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},eS=["ALL",...Object.values(Pe)],Ar=class{constructor(){this.marks=Object.fromEntries(eS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=re();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`,Ui(r,50)],[`${t}_P95`,Ui(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var hg={};z(hg,{initServer:()=>sS,mapFilesToLocalDrive:()=>nu});function nu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,vo[t.id]?{screenshot:vo[t.id]}:{})),Object.keys(So).forEach(t=>{s.assets||={},s.assets[gg[t]]=So[t]}),s.assets||={},s.assets.screenshots=Object.values(vo)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function sS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await ut("multer"),n=typeof t=="string"?t:tS;await su.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(c,l,m){let d=JSON.parse(c.body.metadata||"{}");if(!d.testResultId)return m(new Error("missing testResultId"),"");let u=Dn.join(n,d.testResultId);try{await su.promises.mkdir(u,{recursive:!0})}catch(f){return m(f,"")}return m(null,u)},filename(c,l,m){let{fileName:d}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!d)return m(new Error("missing stepId or fileName"),"");if(u.stepId){let f=Dn.extname(d);return m(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return m(null,d)}})}),o=(0,fg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(c,l)=>{let m=JSON.parse(c.body.metadata||"{}");m.stepId&&(vo[m.stepId]=c.file.path),m.testResultId&&rS.includes(m.subType)&&(So[m.subType]||=[],So[m.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 m=a(o);m.listen(s,e),m.on("error",d),m.on("listening",()=>c(m.address()));function d(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new C(`Port ${s} is already in use`));default:return l(u)}}})}var su,mg,Dn,fg,tS,vo,So,gg,rS,iu=S(()=>{"use strict";su=I(require("fs")),mg=I(require("os")),Dn=I(require("path")),fg=I(require("express"));Y();On();tS=Dn.join(mg.tmpdir(),"testim/rca/"),vo={},So={},gg={"test-log":"consoleLogs","har-file":"networkLogs"},rS=Object.keys(gg)});var nr,ou,Eo,yg=S(()=>{"use strict";nr=I(require("lodash"));B();W();ou=P("override-test-data-builder"),Eo=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):ou.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):ou.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId: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 nr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(m=>this.generateTestUniqId(m)),o=i.indexOf(n),a=i.lastIndexOf(n),c=r[o],l=this.createNewTestItems(c,t);return r.splice(o,a-o+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=re();return{...e,resultId:i,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Io(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Cr,Qe,nS,iS,oS,aS,Ro,bg=S(()=>{"use strict";Cr=I(require("lodash"));B();ae();cs();fs();ge();Y();W();Dt();kn();pg();ys();iu();oe();de();yg();Rn();Qe=P("test-run-status"),nS=wr(),iS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,oS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,aS=rt();Ro=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Ar;var a,c,l,m;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=en(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:Si||t.parallel||1,browser:i,gitBranch:nS,gitCommit:iS,gitRepoUrl:oS,runnerVersion:aS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(d=>d.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:(m=t.gridData)==null?void 0:m.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:m,testStatus:d,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w}=a,b={originalTestResultId:t,previousTestResultId:r,config:Cr.cloneDeep(c),testId:l,status:"QUEUED",name:m,resultId:e,retryCount:o,testStatus:d};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w},lu({projectId:n,runId:i,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,Q.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var l;let{project:n,remoteRunId:i,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Ao(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(m){Qe.error("failed to upload test data artifact (runner)",{err:m})}let c=Cr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,Pr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await Io(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...i},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(i){throw Qe.error("Failed to start test",{err:i}),i}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Qe.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Xe.EVALUATING&&Lt.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Xe.EVALUATING} status`);return}if(l){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,ze(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,n,c)}calcResultText(e){return e.success?fe.PASSED:fe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Xe.QUARANTINE}`)}monitorMemoryUsage(e){let t=Xc();t.isOverThreshold&&Qe.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&nu(o,Qe),o.resultUrl=ze(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Q.onTestFinished(o,e,i);let c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await Io(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){Qe.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,...n},5)}catch(a){throw Qe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=Gc;return e&&(n=i),Qr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g;let c=e.browser?sn(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=Zr(O,n)&&rn(a.nativeApp)&&!e.appId,m=Zt(e)&&(Qr(a.nativeApp,n)||l),d=Ye(a,e)||m,u={testId:a.testId,testOptimization:a.testOptimization,status:d?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,...m&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:c.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await An.end(r,t),e==="mongo"&&await wn.end(t)}async executionStart(e,t,r,n,i){Qe.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:m}=o;gs(()=>Promise.all([this.endKeepAlive(m,t,l),xo("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let d={projectId:t,executionId:e,...O.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await Io(o.beforeSuite,d),f=new Eo(u,Cr.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let w=async()=>{let b=Cr.cloneDeep(this.testRunStatus);await se(Object.keys(b),async A=>{var L;let D=b[A],V=(L=D.config)==null?void 0:L.testData,x=D.testId,R=await Ao(t,x,A,V,c.defaults);R&&(delete D.config.testData,D.config.testDataUrl=R)});let v=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),E=cu({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:v,intersections:o.intersections});return this.executionStartedPromise=E,E.catch(A=>Qe.error(A)),E};try{await w()}catch(b){Qe.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Cr.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 m;let t=Qc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:d,testStatus:u}of t)d===fe.PASSED&&n++,d===fe.SKIPPED&&i++,d===fe.FAILED&&u===Xe.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await Io(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(d){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Qe.warn("error while running afterSuite Hook",{err:d,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await ug(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((m=this.options.lightweightMode)!=null&&m.onlyTestIdsNoSuite))try{return await xo("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(d){throw Qe.error("Failed to update suite finished",{err:d}),d}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await au(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function uu(s){var i;let e=s.canary?"-master.zip":".zip",t=`${ft}/testim-headless${e}`,r=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(i=s.company)==null?void 0:i.companyId,projectId:s.project,runnerEnvironment:At});return r||(cS.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),r=`${ft}/testim-headless.zip`),!(s.ext||s.extensionPath)&&r&&(t=r,s.testimHeadlessExtensionDownloadUrl=r),{chrome:t,"edge-chromium":t}}function Tg(s){let{chrome:e}=uu(s);return e}function Co(s){let e=At==="staging"?`${ft}/staging-sessionPlayer`:`${ft}/sessionPlayer`;return s.canary?`${e}-master`:e}var cS,Nn=S(()=>{"use strict";oe();de();W();cS=P("runOptionsUtils")});function bs(s){var n;let t=(n=new RegExp(`^\\b(${Object.values(pu).join("|")})`).exec(s))==null?void 0:n[0];return t||pu[Rd]||"usw2"}var pu,vg,Po=S(()=>{"use strict";oe();pu={"us-west-2":"usw2","eu-central-1":"euc1"},vg=Object.fromEntries(Object.entries(pu).map(([s,e])=>[e,s]))});function Sg(s,e){if(e){if(!fS.has(e)){Mn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var Eg,Ig,Ht,Rg,xg,Ag,ko,Cg,Mn,lS,uS,Fn,pS,dS,mS,ne,fS,Oo=S(()=>{"use strict";Eg=I(require("ms")),Ig=I(require("p-retry")),Ht=I(require("node:os")),Rg=I(require("portfinder")),xg=I(require("node:child_process"));B();Ge();ge();Ag=I(require("node:fs")),ko=I(require("node:fs/promises")),Cg=require("node:path");Y();W();Nn();ae();de();B();Po();Mn=P("lambdatestService"),lS="https://downloads.lambdatest.com/tunnel/v3",uS={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"},Fn=`${Ht.tmpdir()}/LT`,pS=`${Fn}/LT`,dS=(0,Eg.default)("15m"),mS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===_.TESTIM_LAMBDATEST||e.type===_.LAMBDATEST||e.type===_.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?dS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(pS))return;let t=uS[Ht.platform()+Ht.arch()];if(!t)throw new Error(`tunnel on ${Ht.platform()+Ht.arch()} platform is not supported.`);let r=`${Fn}.zip`;await Je(`${lS}/${t}`,r),await ot(r,Fn)}static async chmodLtTunnel(e){if(!(Ht.platform()==="win32"||!await ye(e))){try{await ko.access(e,Ag.constants.X_OK);return}catch{}try{await ko.chmod(e,"777")}catch(r){throw Mn.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 Rg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;ne.tunnelName=re();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(n&&i)l=[...l,"--user",n,"--key",i];else throw new C("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 C("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await ne.delay(3e3),await ne.chmodLtTunnel((0,Cg.join)(Fn,"LT")),ne.tunnel=xg.spawn("./LT",l,{cwd:Fn});let m="",d="";ne.tunnel.stdout.on("data",u=>{m+=u.toString()}),ne.tunnel.stderr.on("data",u=>{d+=u.toString()});try{let u=await(0,Ig.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(m.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Mn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:m,stderrResult:d}),Mn.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",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,c){var E,A;if(!this.isActive)return{};let l=ne.lambdatestConfig.CAPABILITIES[t]||{},m={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},d=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:Sg(n,a==null?void 0:a.os)||Sg(n,(E=o==null?void 0:o.lt)==null?void 0:E.platform)||l.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??mS,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 D=uu({canary:u});!h&&D[t]&&(d=[...d,D[t]]),h&&De(h)&&(d=[...d,h]),d.length||Mn.warn("No extension was loaded in LambdaTestService",{extUrls:D,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&De(g)&&(d=[...d,g]);let T=bs(e.project||""),b={euc1:"eu"}[T],v=b?{region:b}:{};return{build:r,name:`${n} - ${i}`,...v,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.lambdatestConfig.TIMEZONE,...l,...y,loadExtension:d,...m,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},fS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey","macOS Catalina","macOS Big Sur"])});function hS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Mg(s){return _g.readFileSync(s,{encoding:"base64"})}function Fg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&De(s))&&s){let r=Mg(s);ws.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${gu(r)} current extension count: ${e.length}`),e.push(r)}}function Ug(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let m=typeof s.ext=="string"?s.ext:`${__dirname}/..`,d=r||m,u=`--load-extension=${d}`;ws.info(`adding extension: testim unpacked , path: ${d}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=_o.basename(i));let c=_o.join(process.cwd(),a),l=Mg(c);ws.info(`adding extension: testim zipped, path: ${c} length: ${l.length} hash: ${gu(l)} current extension count: ${e.length}`),e.push(l)}function yS(s,e,t,r,n,i,o,a){var g,y;let c=t.seleniumName||t.browserValue,l=[],m=[...Ng];e.headless&&m.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":mu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":mu.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(fu(n)){let T=O.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&m.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}fu(n)&&c==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>m.push(`--${T}`));try{let T=Lo();T.length&&T.forEach(w=>m.push(`--disable-features=${w}`))}catch{}e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=mu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&m.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&m.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:c});function u(){t.mobileEmulation&&(d.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(),Fg(r,l,o),a===K.EXTENSION&&Ug(e,l,m,i,o),l.length>0&&(d.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=m;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[c],h={MicrosoftEdge:"ms",chrome:"goog"}[c];return ne.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=d),s}function TS(s,e,t){let r={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":kg.join(","),"browser.helperApps.neverAsk.openFile":kg.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 Ts(s){return`${s.width}x${s.height}`}function RS(s){let{platform:e}=s;if(!e)return Ts(Og);let t=e.split(" ")[1];return e.startsWith("Windows")&&IS.has(t)?Ts(vS):e==="Linux"?Ts(wS):e.startsWith("macOS")?Ts(SS):Ts(e==="OS X El Capitan"||e==="OS X Yosemite"?ES:Og)}function xS(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(n["sauce:options"].screenResolution=RS(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let i=(0,Dg.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,pt.merge(i,n,r)}return pt.merge(n,r)}return{}}function AS(s){let{runnerOptions:e}=s;if(pt.isEmpty(e.browserstack))return{};let{projectData:t,testRunConfig:r,testId:n,testName:i,executionId:o,executionName:a}=s,c={buildName:`${a} - ${o}`,sessionName:`${i} - ${n}`,projectName:`${t.name} - ${t.projectId}`,...e.browserstack};return r&&r.browserValue==="safari"&&r.bs.safari_version&&(c.os_version=r.bs.safari_version,r.bs.safari_version==="10"&&Object.assign(c,{"safari.options":{technologyPreview:!0}})),c}function CS(s){return s.perfecto?s.perfecto:{}}function PS(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 kS(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,i=r||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=hc(i,o)),a}function Lo(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function Do(s){var A,D,V,x;let{overrideConfiguration:e,browserOptions:t,testId:r,testName:n,testRunConfig:i,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:m,testResultId:d,lambdatestService:u,mode:f}=s;if(o.mode==="local"){let R=[],L=[...Ng],M={};t.headless&&L.push("--headless"),t.silentDebuggerExtensionApi&&L.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&L.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let H=Lo();H.length&&H.forEach(j=>L.push(`--disable-features=${j}`))}catch{}return t.chromeExtraArgs&&t.chromeExtraArgs.forEach(H=>L.push(`--${H}`)),t.chromeBinaryLocation&&(M.binary=t.chromeBinaryLocation),f!==K.SELENIUM&&Ug(t,R,L,null,u),Fg(a,R,u),{logLevel:Pg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:L,extensions:R,...M},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:h,driverRequestRetries:g}=t,y=kS(t,o),T={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Pg,connectionRetryTimeout:h,connectionRetryCount:g,getSessionTimeout:Math.max(u.getSessionTimeout,t.getSessionTimeout),getSessionRetries:u.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!pt.isEmpty(y)&&{headers:y},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};fu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,T.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(T.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 w=Number(t.browserTimeout/1e3),b=t.browser||(i==null?void 0:i.browserValue),v={runnerOptions:t,testId:r,testName:n,testRunConfig:i,executionId:c,executionName:l,projectData:m};pt.merge(T.desiredCapabilities,xS(t,n,i),AS(v),CS(t),PS(t,b,w),u==null?void 0:u.getCapabilities(t,b,c,d,n,i,e,f));let E=null;switch(!t.ext&&!t.extensionPath&&((A=o.host)!=null&&A.endsWith(".testim.io"))&&!t.canary&&f===K.EXTENSION&&(b==="chrome"||b==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(E="/opt/testim-headless"),b){case"chrome":case"edge-chromium":T=bS(T,t,i,a,o,E,u,f);break;case"firefox":T=TS(T,t,u);break;case"safari":case"safari technology preview":T=hS(T,b);break;default:break}pt.merge(T.desiredCapabilities,t.seleniumCapsFileContent);try{let R={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},L=q=>q[o.provider]||q[T.host]||q[R[T.host]],M=q=>{var ie,Ie;return L(q)||q[(ie=T.desiredCapabilities)==null?void 0:ie.browserName]||q[(Ie=T.desiredCapabilities)==null?void 0:Ie.version]||q||{}},H=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),j=M(M(H));Object.keys(j).length&&(ws.info(`Adding custom capabilities: ${JSON.stringify(j)}`),Object.assign(T.desiredCapabilities,j))}catch(R){ws.error("Failed to load custom capabilities",{error:R,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(T.desiredCapabilities&&!T.capabilities&&(gS(T),T.capabilities={alwaysMatch:T.desiredCapabilities,firstMatch:[{}]},delete T.desiredCapabilities),T.hostname=T.host,s.printFinalCaps){let R=(D=T.capabilities)==null?void 0:D.alwaysMatch,L=JSON.parse(JSON.stringify(T)),M=(V=L==null?void 0:L.capabilities)==null?void 0:V.alwaysMatch,H=q=>q.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(q=>{var ie,Ie;M!=null&&M[q]&&(M[q].extensions=(Ie=(ie=R==null?void 0:R[q])==null?void 0:ie.extensions)==null?void 0:Ie.map(H))}),M!=null&&M.loadExtension&&(M.loadExtension=(x=R==null?void 0:R.loadExtension)==null?void 0:x.map(H));let j=require("node:util");console.log(j.inspect(L,{showHidden:!1,depth:null,colors:!0}))}return T}var _g,_o,Lg,pt,Dg,ws,Pg,mu,Ng,gu,fu,gS,bS,kg,Og,wS,vS,SS,ES,IS,No=S(()=>{"use strict";_g=I(require("node:fs")),_o=I(require("node:path")),Lg=I(require("node:crypto")),pt=I(require("lodash"));B();oe();W();de();ae();Oo();Dg=require("lodash"),ws=P("testim-desired-capabilities-builder"),Pg=vi?"debug":"silent",mu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Ng=["--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"],gu=(...s)=>Lg.createHash("sha256").update(s.join("")).digest("hex"),fu=s=>s.type===_.DEVICE_FARM||s.type===_.HYBRID&&s.provider==="devicefarm",gS=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=O.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ws.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};bS=pt.memoize(yS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(pt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return gu(o,a,c,r,l,i)}),kg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Og={width:1920,height:1080},wS={width:1920,height:1200},vS={width:2560,height:1600},SS={width:2360,height:1770},ES={width:2048,height:1536},IS=new Set(["7","8","8.1","10","11"])});function Ue(s){var e,t,r,n,i,o,a,c;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||((t=s.message)==null?void 0:t.toLowerCase())==="unknown error"||((r=s.message)==null?void 0:r.match(/Unknown timeout type/))||s.name==="unknown command"||((n=s.message)==null?void 0:n.match(/did not match a known command/))||((i=s.message)==null?void 0:i.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=s.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((c=s.message)==null?void 0:c.match(/\.\w* is not a function/))}function jg(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 hu=S(()=>{"use strict"});function yu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function i(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return i(y,f)}function o(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=i(u,"stroke-width");return!!g&&parseInt(g,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(u){return i(u,"overflow")==="hidden"}function c(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:c(f))}function l(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:l(u.parentNode):!1}if(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return yu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let m=!!n(s,u=>Number(i(u,"opacity"))===0),d=!!n(s,u=>i(u,"display")==="none");return!(m||d||!o(s)||c(s))}var $g=S(()=>{"use strict"});var Wg,Vg,qt,OS,_S,Mo,Gg=S(()=>{"use strict";Wg=I(require("promise-queue")),Vg=I(require("webdriverio"));oe();$e();B();W();Hr();$g();hu();ys();qt=P("WebDriverApi"),OS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},_S={implicit:0,pageLoad:1,script:2},Mo=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,i=t?t.toString().slice(0,2e3):"";throw qt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),wc!==void 0&&(e=wc);let t=1/0;this.queue=new Wg.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,a,c,l,m,d,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),F("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((d=(m=(l=(c=e.capabilities.alwaysMatch)==null?void 0:c["goog:chromeOptions"])==null?void 0:l.extensions)==null?void 0:m[0])==null?void 0:d.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(Pe.GET_BROWSER);try{await this.addToQueue(async()=>{qt.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),F("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await Vg.remote(e),this.logGridStatus(r)}),F("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,Pe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){qt.info("grid status is not supported by the grid",{testResultId:e});return}qt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),qt.info("grid status",{gridStatusMsg:i.message,ready:i.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){qt.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(Ue(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Ue(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Pe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,Pe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Pe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Ne(e)))}finally{this.seleniumPerfStats.markEnd(t,Pe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(yu,{ELEMENT:e,[Jt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ue(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(jg(e,this.isSafari(),qt))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let i=[];return i[_S[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(Ue(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Ne(e)),await this.elementIdValue(Ne(e),t)}async getViewportSize(e){let t=await this.execute(OS);if(typeof e=="string"&&/(width|height)/.test(e)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Ne(e))})}submitFormManually(e){return this.addToQueue(async()=>{var i;let t=await((i=this.client)==null?void 0:i.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let i=await this.client.$(e);await this.client.action("pointer").move({origin:i}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,o),n=async()=>await this.client._setWindowSize(i,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(i){if(Ue(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){qt.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 qt.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 ir={};z(ir,{getSessionPlayer:()=>Z,options:()=>Tu});var Fo,Tu,bu,Z,we=S(()=>{"use strict";Fo=require("path");W();Tu={playerPath:void 0},Z=()=>{if(bu)return bu;let s=($e(),qe(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(dn(),qe(pn)),t=e(),r=Tu.playerPath?(0,Fo.resolve)(Tu.playerPath,"src/background/sessionPlayerInit.ts"):(0,Fo.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),bu=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(Jd),n}});var Hg={};z(Hg,{doubleClick:()=>LS});var LS,qg=S(()=>{"use strict";LS=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function f(w,b,v){return v>w&&v<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},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},m=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},d=function(u){let f=o(u),h=u.event;return t.includes(h)?c(h,f.x,f.y):l(h,f.x,f.y)};try{n.map(f=>d(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=m();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Un={};z(Un,{dispatchFocus:()=>DS});function DS(s,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function r(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let i=getLocatedElement(s);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Bn=S(()=>{"use strict"});var Yg={};z(Yg,{WebDriver:()=>_r});async function US(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 MS(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var vs,Jg,Xg,Be,or,NS,zg,MS,kr,FS,Kg,Or,_r,jn=S(()=>{"use strict";vs=I(require("lodash"));B();$e();No();Jg=I(require("p-retry")),Xg=I(require("ua-parser-js"));Hr();W();hu();Gg();Y();de();ys();Be=P("webdriver"),[or,NS]=[0,2],{extractElementId:zg,getCdpAddressForHost:MS}=X,kr=()=>(we(),qe(ir)).getSessionPlayer().codeSnippets,FS=()=>(we(),qe(ir)).getSessionPlayer().locatorBuilderUtils,Kg=()=>(we(),qe(ir)).getSessionPlayer().utils,Or=()=>(we(),qe(ir)).getSessionPlayer().positionUtils;_r=class extends Mo{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 A,D,V,x,R,L,M,H;let{projectData:r,overrideConfiguration:n,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:m,executionId:d,executionName:u,testResultId:f,seleniumPerfStats:h,fastInit:g,lambdatestService:y,printFinalCaps:T,mode:w}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((V=(D=(A=i==null?void 0:i.company)==null?void 0:A.activePlan)==null?void 0:D.premiumFeatures)==null?void 0:V.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let b=Do({projectData:r,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:m,executionId:d,executionName:u,testResultId:f,lambdatestService:y,overrideConfiguration:n,printFinalCaps:T,mode:w});b.desiredCapabilities&&delete b.desiredCapabilities.marionette,b.capabilities&&delete b.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(y==null?void 0:y.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=h;let v=g?0:1500,E=g?()=>null:()=>this.executeJS("window.focus()");try{F("before initClient in webdriver.js init");let j=await this.initClient(b,a,f);F("after initResult before getCdpAddress in init"),this.cdpUrl=await US(j),F("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await pe(v),O.flags.dontFocusOnInit.isEnabled()||await E(),F("after focus and delay in webdriver.js init")}catch(j){let q=JSON.stringify(vs.omit(b,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:j,capabilitiesAsString:q});let ie=((R=(x=i==null?void 0:i.company)==null?void 0:x.activePlan)==null?void 0:R.plan)==="free";throw(L=j.stack)!=null&&L.includes("at startWebDriverSession")&&((M=j.message)!=null&&M.startsWith("Failed to create session"))&&((H=j.message)!=null&&H.includes("Timeout awaiting 'request'"))&&ie?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(j.message)?new zr(j.message):/capabilit(y|ies)/.test(j.message)?new xi(j.message):/403 Forbidden/.test(j.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(j.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${j.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>vs.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,c)=>{let l=this._keepAliveRequests.find(m=>m.id===c);l&&(l[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=re();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,Be.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Be.warn("failed to click on alert",{err:c}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.handleThresholdBasedError(this.browserClosedCallbacks,a)}else this.generalKeepAliveFailures++,this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures>=3&&this.handleThresholdBasedError(this.keepAliveFailedCallbacks,a)}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}handleThresholdBasedError(t,r){t.forEach(n=>{try{n(r)}catch{}})}async switchToLocatedFrame(t){let r=await this.getElement(t),n=zg(r.value);return await this.switchToFrame({ELEMENT:n,[Jt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new Ai:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(Pe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Pe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
19
+ var fn = ${kr().getLocatedElementCode};
20
20
  return fn.apply(null, arguments);
21
21
  `,t)}finally{this.seleniumPerfStats.markEnd(r,Pe.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,Pe.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...n){return await this.timeouts("script",r),await this.executeAsync(t,...n)}async markDynamicParent(t,r){function n({attributeName:i,attributeValue:o,locatedElement:a}){let c=getLocatedElement(a);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(i,o)}await this.executeJS(`
22
- var getLocatedElement = ${Pr().getLocatedElementCode};
22
+ var getLocatedElement = ${kr().getLocatedElementCode};
23
23
  var setDynamicParentAttribute = ${n.toString()};
24
24
  return setDynamicParentAttribute.apply(null, arguments)
25
- `,{attributeName:MS().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(n){let i=getLocatedElement(n);if(!i)return null;let o=parseInt(window.getComputedStyle(i).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(i).paddingLeft.replace("px",""),10)||0,c=i.getBoundingClientRect();return{top:Math.round(c.top+o),left:Math.round(c.left+a)}}return this.executeJS(`
26
- const getLocatedElement = ${Pr().getLocatedElementCode};
25
+ `,{attributeName:FS().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(n){let i=getLocatedElement(n);if(!i)return null;let o=parseInt(window.getComputedStyle(i).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(i).paddingLeft.replace("px",""),10)||0,c=i.getBoundingClientRect();return{top:Math.round(c.top+o),left:Math.round(c.left+a)}}return this.executeJS(`
26
+ const getLocatedElement = ${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(n){let i=getLocatedElement(n);if(!i)return null;let o=i.getBoundingClientRect();return{bottom:Math.round(o.bottom),height:Math.round(o.height),x:Math.round(o.left),right:Math.round(o.right),y:Math.round(o.top),width:Math.round(o.width)}}return this.executeJS(`
30
- const getLocatedElement = ${Pr().getLocatedElementCode};
30
+ const getLocatedElement = ${kr().getLocatedElementCode};
31
31
  const getLocation = ${r.toString()};
32
32
  return getLocation.apply(null, arguments)
33
- `,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function r(i,o){function a(u){var h;return(h=u.childNodes)!=null&&h.length&&[...u.childNodes].filter(g=>g.nodeType===Node.ELEMENT_NODE).forEach(g=>{typeof g.tagName=="string"&&g.tagName.toLowerCase()==="title"?u.removeChild(g):a(g)}),u}function c(u){return["INPUT","TEXTAREA"].includes(u.tagName)}function l(u){var f,h,g;try{if(u.shadowRoot&&!((g=(h=Object.getOwnPropertyDescriptor((f=u.ownerDocument.defaultView)==null?void 0:f.Node.prototype,"textContent"))==null?void 0:h.get)!=null&&g.toString().includes("[native code]")))return u.shadowRoot.textContent.replace(/(\r\n|\n|\r)/gm,"")}catch{}if(o&&Array.prototype.some.call(u.children,y=>y.hidden)){let y=u.cloneNode(!0);return Array.prototype.filter.call(y.children,v=>v.hidden).forEach(v=>y.removeChild(v)),y.textContent.replace(/(\r\n|\n|\r)/gm,"")}return u.textContent.replace(/(\r\n|\n|\r)/gm,"")}function m(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 d=getLocatedElement(i);return d?m(d):""}let{value:n}=await this.executeJS(`
34
- const getLocatedElement = ${Pr().getLocatedElementCode};
33
+ `,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function r(i,o){function a(u){var h;return(h=u.childNodes)!=null&&h.length&&[...u.childNodes].filter(g=>g.nodeType===Node.ELEMENT_NODE).forEach(g=>{typeof g.tagName=="string"&&g.tagName.toLowerCase()==="title"?u.removeChild(g):a(g)}),u}function c(u){return["INPUT","TEXTAREA"].includes(u.tagName)}function l(u){var f,h,g;try{if(u.shadowRoot&&!((g=(h=Object.getOwnPropertyDescriptor((f=u.ownerDocument.defaultView)==null?void 0:f.Node.prototype,"textContent"))==null?void 0:h.get)!=null&&g.toString().includes("[native code]")))return u.shadowRoot.textContent.replace(/(\r\n|\n|\r)/gm,"")}catch{}if(o&&Array.prototype.some.call(u.children,y=>y.hidden)){let y=u.cloneNode(!0);return Array.prototype.filter.call(y.children,w=>w.hidden).forEach(w=>y.removeChild(w)),y.textContent.replace(/(\r\n|\n|\r)/gm,"")}return u.textContent.replace(/(\r\n|\n|\r)/gm,"")}function m(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 d=getLocatedElement(i);return d?m(d):""}let{value:n}=await this.executeJS(`
34
+ const getLocatedElement = ${kr().getLocatedElementCode};
35
35
  const extractText = ${r.toString()};
36
36
  return extractText.apply(null, arguments)
37
- `,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var i,o;let r=Pr().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(Pe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,Pe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,Pe.GET_HTML);let c=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(o=(i=this.client)==null?void 0:i.requestHandler)!=null&&o.sessionID||Object.assign(c,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),c}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class i extends Error{}function o(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,zg.default)(async()=>{let{value:l}=await this.windowHandleSize(),{value:m}=await this.execute(o),d=l.width-m.screenWidth,u=l.height-m.screenHeight;await this.windowHandleSize({width:t.width+d,height:t.height+u});let{value:f}=await this.execute(o);if(f.screenWidth!==t.width||f.screenHeight!==t.height)throw new i},{retries:5-1,factor:1,minTimeout:0}).catch(l=>{if(!(l instanceof i))throw l});if(typeof t!="object"||typeof t.width!="number"||typeof t.height!="number"||r!==void 0&&typeof r!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(r===void 0?!0:r)?a():this.windowHandleSize(t)}setViewportSize(t,r){return this.setViewportSizeNEW({width:t,height:r},!0)}getBrowserMajorVersion(t){var r;try{return parseInt(((r=t.browser)==null?void 0:r.version)||"0",10)}catch(n){return Be.error("failed to get browser version",{err:n}),0}}async getBrowserAndOS(){function t(a){let c=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(c[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(c[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";c=c[2]?[c[1],c[2]]:[a.appName,a.appVersion,"-?"];let l=a.match(/version\/(\d+)/i);return l!==null&&c.splice(1,1,l[1]),c[0].toLowerCase()}if(this.browserAndOS)return this.browserAndOS;function r(){var a;return(a=window==null?void 0:window.navigator)!=null&&a.userAgent?window.navigator.userAgent:"unknown"}let{value:n}=await this.executeJS(r),i=(0,Kg.default)(n),o=i.os;return this.browserAndOS={os:`${o.name} ${o.version}`,browserMajor:this.getBrowserMajorVersion(i),browser:t(n),userAgent:n,browserVersion:i.browser.version},this.browserAndOS}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:n,clickOffset:i}=t,o=kr().calculateElementMiddlePoint(n),a=i.x,c=i.y;return!qg().isWithinBounds(n.left,n.left+n.width,o.x+a)||!qg().isWithinBounds(n.top,n.top+n.height,o.y+c)?(Be.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,c,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:n,clickOffset:i}=t,o=n.left+i.x+r.x,a=n.top+i.y+r.y;return{x:o,y:a}}async actWithActionsAPI(t,r,n,i){let o=this.getRelativeMoveActions(t,n),a=this.getClickActions(i,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(a)}])}catch(c){Be.error("tried to use element origin but failed because of visibility, trying absolute",c);let{x:l,y:m}=this.computeAbsoluteMovement(t),d=this.getMoveActions(l,m);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:d.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,or,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(Gg(),Vg)),Promise.resolve().then(()=>(Un(),Fn))]);return this.executeCodeAsync(`
38
- var getLocatedElement = ${Pr().getLocatedElementCode};
37
+ `,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var i,o;let r=kr().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(Pe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,Pe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,Pe.GET_HTML);let c=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(o=(i=this.client)==null?void 0:i.requestHandler)!=null&&o.sessionID||Object.assign(c,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),c}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class i extends Error{}function o(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,Jg.default)(async()=>{let{value:l}=await this.windowHandleSize(),{value:m}=await this.execute(o),d=l.width-m.screenWidth,u=l.height-m.screenHeight;await this.windowHandleSize({width:t.width+d,height:t.height+u});let{value:f}=await this.execute(o);if(f.screenWidth!==t.width||f.screenHeight!==t.height)throw new i},{retries:5-1,factor:1,minTimeout:0}).catch(l=>{if(!(l instanceof i))throw l});if(typeof t!="object"||typeof t.width!="number"||typeof t.height!="number"||r!==void 0&&typeof r!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(r===void 0?!0:r)?a():this.windowHandleSize(t)}setViewportSize(t,r){return this.setViewportSizeNEW({width:t,height:r},!0)}getBrowserMajorVersion(t){var r;try{return parseInt(((r=t.browser)==null?void 0:r.version)||"0",10)}catch(n){return Be.error("failed to get browser version",{err:n}),0}}async getBrowserAndOS(){function t(a){let c=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(c[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(c[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";c=c[2]?[c[1],c[2]]:[a.appName,a.appVersion,"-?"];let l=a.match(/version\/(\d+)/i);return l!==null&&c.splice(1,1,l[1]),c[0].toLowerCase()}if(this.browserAndOS)return this.browserAndOS;function r(){var a;return(a=window==null?void 0:window.navigator)!=null&&a.userAgent?window.navigator.userAgent:"unknown"}let{value:n}=await this.executeJS(r),i=(0,Xg.default)(n),o=i.os;return this.browserAndOS={os:`${o.name} ${o.version}`,browserMajor:this.getBrowserMajorVersion(i),browser:t(n),userAgent:n,browserVersion:i.browser.version},this.browserAndOS}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:n,clickOffset:i}=t,o=Or().calculateElementMiddlePoint(n),a=i.x,c=i.y;return!Kg().isWithinBounds(n.left,n.left+n.width,o.x+a)||!Kg().isWithinBounds(n.top,n.top+n.height,o.y+c)?(Be.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,c,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:n,clickOffset:i}=t,o=n.left+i.x+r.x,a=n.top+i.y+r.y;return{x:o,y:a}}async actWithActionsAPI(t,r,n,i){let o=this.getRelativeMoveActions(t,n),a=this.getClickActions(i,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(a)}])}catch(c){Be.error("tried to use element origin but failed because of visibility, trying absolute",c);let{x:l,y:m}=this.computeAbsoluteMovement(t),d=this.getMoveActions(l,m);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:d.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,or,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(qg(),Hg)),Promise.resolve().then(()=>(Bn(),Un))]);return this.executeCodeAsync(`
38
+ var getLocatedElement = ${kr().getLocatedElementCode};
39
39
  var dispatchFocus = ${n.toString()};
40
40
  var doubleClick = ${r.toString()};
41
41
  var eventData = arguments[0];
42
42
  var done = arguments[1];
43
43
  return doubleClick.call(null, eventData, done);
44
- `,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,or,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,DS,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(Ue(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw n}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(n){if(Ue(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw n}}async dragAndDropOldAPI(t,r){return await this.moveTo(t),await this.buttonDown(),await this.moveTo(r),await this.buttonUp()}async calculateElementMiddlePoint(t,r={top:0,left:0}){let n=await this.getLocatedElementRect(t);if(!(n!=null&&n.value))throw Be.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:i,y:o,width:a,height:c}=n.value;return{x:r.left+i+a/2,y:r.top+o+c/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:i}=r.clickOffset;try{return await this.moveTo(t,n,i)}catch(o){if(Ue(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,n="viewport",i=0){return[{type:"pointerMove",duration:i,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){Be.error("tried to use element origin but failed because of visibility, trying location",n);let i=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(i)}}getDragCoordinates(t){let r=t.filter(o=>o.event==="mousemove"||o.event==="pointermove"),n=r[0].pointerPosition,i=r.at(-1).pointerPosition;return{xDiff:i.screenX-n.screenX,yDiff:i.screenY-n.screenY}}async dragWithMoveTo(t,r,n,i,o){return await this.moveTo(t,i,o),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,i,o){let a=this.getMoveActions(i,o,t,1),c=this.getClickActions(["pointerDown"],or),l=this.getMoveActions(r,n,"pointer",1),m=this.getClickActions(["pointerUp"],or);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(c).concat(l).concat(m)}])}async drag(t,r,n,i,o){let{width:a,height:c}=r,l=n-a/2+1,m=i-c/2,d=this.getDragCoordinates(o),{xDiff:u,yDiff:f}=d;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,l,m);try{return await this.dragWithMoveTo(t,u,f,l,m)}catch(h){if(Ue(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,l,m);throw h}}getMoveRelativeSequence(t,r,n,i){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},c={x:n,y:i},l=10,m=Math.round(o(a,c)/l),d=Array.from({length:m},()=>({x:Math.round((c.x-a.x)/m),y:Math.round((c.y-a.y)/m)}));return[{x:1,y:1}].concat(d)}getMoveAbsoluteSequence(t,r,n,i){return this.getMoveRelativeSequence(t,r,n,i).reduce((a,c)=>{let l=a.at(-1);return a.concat({x:Math.round(l.x+c.x),y:Math.round(l.y+c.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:i,fromX:o,fromY:a,toRect:c,toX:l,toY:m}=n,d=kr().calculateElementMiddlePoint(i),u=kr().calculateElementMiddlePoint(c),f=this.getMoveRelativeSequence(d.x+o,d.y+a,u.x+l,u.y+m);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(m)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:c}=t,l=kr().calculateElementMiddlePoint(r),m=kr().calculateElementMiddlePoint(o),d=Math.floor(l.x+n),u=Math.floor(l.y+i),f=Math.floor(m.x+a),h=Math.floor(m.y+c),g=this.getMoveAbsoluteSequence(d,u,f,h),y=this.getMoveActions(d,u),T=this.getClickActions(["pointerDown"],or),v=vs.flatMap(g,A=>this.getMoveActions(A.x,A.y)),b=this.getMoveActions(f,h),w=this.getClickActions(["pointerUp"],or),S=y.concat(T).concat(v).concat(b).concat(w);return this.actions([{type:"pointer",id:"mouse",actions:S}])}async dragAndDrop(t,r,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,r,n)}catch(i){if(Ue(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw i}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(i){if(Ue(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw i}}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(i){if(Ue(i))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw i}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:c}=t,l=kr().calculateElementMiddlePoint(r),m=kr().calculateElementMiddlePoint(o),d=Math.floor(l.x+n),u=Math.floor(l.y+i),f=Math.floor(m.x+a),h=Math.floor(m.y+c);await this.moveWithActionsAPI({x:d,y:u});let g=this.getClickActionList(["pointerDown"],or);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],or);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(Hg(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(i){Be.error("error getting element location",{err:i})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){Be.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Be.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(Ue(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var bu,Tu,jn,wu=E(()=>{"use strict";$();de();ge();bu=P("lab-features-service"),Tu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(bu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await vu(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){bu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=O.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:i}=this,o=n.find(c=>c.featureFlagName===e),a=o==null?void 0:o.enabled;return Boolean(i&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw bu.error(t,{featureFlagName:e.name}),new Error(t)}},jn=new Tu});function US(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function BS(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:r}=globalThis.require("path"),{promises:n}=globalThis.require("fs");return{sync:!1,lib:n.readFile(`${s}${t}package.json`).then(o=>{let a=JSON.parse(o);return import(r(s,a.main||`${t}index.js`))})}}}function jS(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function $S(s,e,t,r,n={},i=void 0,o=void 0){let a=Object.keys(n).map(h=>`
45
- var res = requireOrImportMethod('${US(n[h])}');
44
+ `,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,or,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,NS,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(Ue(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw n}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(n){if(Ue(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw n}}async dragAndDropOldAPI(t,r){return await this.moveTo(t),await this.buttonDown(),await this.moveTo(r),await this.buttonUp()}async calculateElementMiddlePoint(t,r={top:0,left:0}){let n=await this.getLocatedElementRect(t);if(!(n!=null&&n.value))throw Be.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:i,y:o,width:a,height:c}=n.value;return{x:r.left+i+a/2,y:r.top+o+c/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:i}=r.clickOffset;try{return await this.moveTo(t,n,i)}catch(o){if(Ue(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,n="viewport",i=0){return[{type:"pointerMove",duration:i,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){Be.error("tried to use element origin but failed because of visibility, trying location",n);let i=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(i)}}getDragCoordinates(t){let r=t.filter(o=>o.event==="mousemove"||o.event==="pointermove"),n=r[0].pointerPosition,i=r.at(-1).pointerPosition;return{xDiff:i.screenX-n.screenX,yDiff:i.screenY-n.screenY}}async dragWithMoveTo(t,r,n,i,o){return await this.moveTo(t,i,o),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,i,o){let a=this.getMoveActions(i,o,t,1),c=this.getClickActions(["pointerDown"],or),l=this.getMoveActions(r,n,"pointer",1),m=this.getClickActions(["pointerUp"],or);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(c).concat(l).concat(m)}])}async drag(t,r,n,i,o){let{width:a,height:c}=r,l=n-a/2+1,m=i-c/2,d=this.getDragCoordinates(o),{xDiff:u,yDiff:f}=d;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,l,m);try{return await this.dragWithMoveTo(t,u,f,l,m)}catch(h){if(Ue(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,l,m);throw h}}getMoveRelativeSequence(t,r,n,i){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},c={x:n,y:i},l=10,m=Math.round(o(a,c)/l),d=Array.from({length:m},()=>({x:Math.round((c.x-a.x)/m),y:Math.round((c.y-a.y)/m)}));return[{x:1,y:1}].concat(d)}getMoveAbsoluteSequence(t,r,n,i){return this.getMoveRelativeSequence(t,r,n,i).reduce((a,c)=>{let l=a.at(-1);return a.concat({x:Math.round(l.x+c.x),y:Math.round(l.y+c.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:i,fromX:o,fromY:a,toRect:c,toX:l,toY:m}=n,d=Or().calculateElementMiddlePoint(i),u=Or().calculateElementMiddlePoint(c),f=this.getMoveRelativeSequence(d.x+o,d.y+a,u.x+l,u.y+m);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(m)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:c}=t,l=Or().calculateElementMiddlePoint(r),m=Or().calculateElementMiddlePoint(o),d=Math.floor(l.x+n),u=Math.floor(l.y+i),f=Math.floor(m.x+a),h=Math.floor(m.y+c),g=this.getMoveAbsoluteSequence(d,u,f,h),y=this.getMoveActions(d,u),T=this.getClickActions(["pointerDown"],or),w=vs.flatMap(g,A=>this.getMoveActions(A.x,A.y)),b=this.getMoveActions(f,h),v=this.getClickActions(["pointerUp"],or),E=y.concat(T).concat(w).concat(b).concat(v);return this.actions([{type:"pointer",id:"mouse",actions:E}])}async dragAndDrop(t,r,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,r,n)}catch(i){if(Ue(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw i}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(i){if(Ue(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw i}}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(i){if(Ue(i))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw i}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:c}=t,l=Or().calculateElementMiddlePoint(r),m=Or().calculateElementMiddlePoint(o),d=Math.floor(l.x+n),u=Math.floor(l.y+i),f=Math.floor(m.x+a),h=Math.floor(m.y+c);await this.moveWithActionsAPI({x:d,y:u});let g=this.getClickActionList(["pointerDown"],or);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],or);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},n;try{n=await this.getElementLocation(t)}catch(i){Be.error("error getting element location",{err:i})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){Be.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Be.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(Ue(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var wu,vu,$n,Su=S(()=>{"use strict";W();de();ge();wu=P("lab-features-service"),vu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(wu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await Eu(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){wu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=O.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:i}=this,o=n.find(c=>c.featureFlagName===e),a=o==null?void 0:o.enabled;return Boolean(i&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw wu.error(t,{featureFlagName:e.name}),new Error(t)}},$n=new vu});function BS(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function jS(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:r}=globalThis.require("path"),{promises:n}=globalThis.require("fs");return{sync:!1,lib:n.readFile(`${s}${t}package.json`).then(o=>{let a=JSON.parse(o);return import(r(s,a.main||`${t}index.js`))})}}}function $S(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function WS(s,e,t,r,n={},i=void 0,o=void 0){let a=Object.keys(n).map(h=>`
45
+ var res = requireOrImportMethod('${BS(n[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
- ${Qg.default.toString()}
52
+ ${eh.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
  `,m=`
107
107
  function injectCode(params, args, incomingParams, context, code) {
108
- const constructWithArguments = ${jS.toString()}
108
+ const constructWithArguments = ${$S.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 = ${BS.toString()}
174
+ const requireOrImportMethod = ${jS.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 = ${Rc.toString()}
183
+ const isPromise = ${Cc.toString()}
184
184
 
185
185
  parentPort.once('message', input => {
186
186
  const { incomingParams, context, code } = input;
@@ -209,47 +209,47 @@ Testim had missing write access to ${r||e}
209
209
  injectCode(params, args, incomingParams, context, code);
210
210
  });
211
211
  })();
212
- `,u=[],f=new Zg.Worker(d,{eval:!0});try{return await le(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};dt.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?dt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):dt.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",()=>{dt.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),i)}catch(h){if(!(h instanceof ce))throw h;return dt.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 WS(s){try{await Xg.promises.rm(s,{recursive:!0,force:!0})}catch(e){dt.warn("failed to remove install npm packages folder",{err:e})}}function eh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function Es(s,e,t,r,n,i){let o=eh(n,e,s,t),{data:a}=await VS(o,r,i);return a}async function Is(s,e,t,r,n,i,o,a,c,l){var g;let m=r.computePackagePathFromPackageJsonExports||O.flags.computePackagePathFromPackageJsonExports.isEnabled(),d=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(m){let T=Wm(y.testimPackageLocalLocation);return[y.paramName,Ss.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=eh(o,n,e,i);if(l){let y=await _n(l);y&&(c=y)}Buffer.isBuffer(c)&&(dt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let f="data:,";return c==="data:"&&(dt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=f),{...await $S(u,t,r,s,d,a,c),nodeVersion:process.version}}async function VS(s,e,t){let r=e.map(l=>`${l.packageName}@${l.packageVersion}`),n=th(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?n:Ss.join(n,`/${s}`),a=global.proxyUri;async function c(){let l="";try{if(l=await sl(o,r,a,t),dt.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(d=>{let u=jm(o,d.packageName);return{...d,packageFullName:`${d.packageName}@${u}`,packageLocalLocation:Ss.resolve(o,"node_modules",d.packageName)}}),installFolder:o}}catch(m){throw dt.warn("npm package install failed",{transactionId:s,err:m}),m}}try{return await le(c(),t)}catch(l){throw l instanceof ce&&dt.warn("timeout to install package",{packages:r,transactionId:s,err:l,timeout:t}),l}}function th(){return Ss.join(Yg.tmpdir(),"/testim_local_packages")}function GS(){let s=th();return WS(s)}var Xg,Yg,Ss,Qg,Zg,dt,Rs=E(()=>{"use strict";Xg=I(require("fs")),Yg=I(require("os")),Ss=I(require("path"));B();os();Qg=I(require("data-uri-to-buffer")),Zg=require("worker_threads");Y();$();ge();os();de();dt=P("cli-service");GS().catch(s=>dt.warn("failed to clean local package folder",{err:s}))});var ar={};z(ar,{run:()=>qS});function HS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var qS,rh=E(()=>{"use strict";Rs();Y();de();qS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:m,fileDataUrl:d,s3filepath:u}=e.data;try{let f=await Is(r,n,i,o,a,c,l,m,d,u);return f&&HS({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 Su={};z(Su,{run:()=>zS});var zS,sh=E(()=>{"use strict";Rs();Y();zS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await Es(t,r,n,o,i,a),success:!0}}catch(c){if(c instanceof Ct)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof ce)return{success:!1,code:"timeout"};throw c}}});async function ih(s,e,t,r){try{return await Eu(s,e,t,r)}catch{Mo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function JS(s,e,t,r,n){return Mo.info("finished to run remote step",{stepId:t,sessionId:n}),await ih(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function nh(s,e,t,r,n){return Mo.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await ih(s,e,t,{status:"completed",success:!1,failureReason:r})}async function oh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),c=t.id;Mo.info("start play remote step",{stepType:o,stepId:c,sessionId:a});let l=KS[o];if(!l)return await nh(n,r,c,`Failed to find step type ${o}`,a);try{let m=await l.run(e,t,i);return await JS(n,r,c,m,a)}catch(m){return await nh(n,r,c,m.message,a)}}var Mo,KS,ah=E(()=>{"use strict";rh();ge();sh();$();Mo=P("step-playback"),KS={"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":ar,"cli-download-code-step":ar,"node-package":Su}});var lh={};z(lh,{preloadTests:()=>Wn});async function Wn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await kt(async()=>{let t=await se(s.testId,r=>Vn({...e,testId:r}),{concurrency:2});return ch.keyBy(t,"testData.id")},"loadTests",YS,[e,s.testId])()}var ch,YS,Fo=E(()=>{"use strict";ch=I(require("lodash"));er();ge();B();YS=1e3*60*60*10});var Iu,uh,_r,QS,Ru,vt,Uo=E(()=>{"use strict";B();ct();Iu=I(require("ws")),uh=require("events");$();oe();_r=P("socket-service"),QS=5e3,Ru=class extends uh.EventEmitter{constructor(){super(...arguments);this.clientId=re();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){_r.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),QS)}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){_r.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(xd);return Ot().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Iu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return _r.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{_r.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Iu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{_r.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){_r.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){_r.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(c){n(c)&&i(c)}(Array.isArray(r)?r:[r]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=o.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=re(),c={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",l=>l.id===a,o),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},vt=new Ru});var dh,xu,ZS,eE,tE,ph,Bo,xs,Au=E(()=>{"use strict";dh=I(require("p-retry")),xu=I(require("socket.io-client"));oe();B();$();ZS=50,eE=10,tE=5e3,ph=10*1e3,Bo=P("base socket service"),xs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Bo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Bo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===eE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=ZS)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",()=>{Bo.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:ph,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${he()}/${t}`,this._socket=xu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:ph,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=xu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,dh.default)(()=>le(n(),tE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Bo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var mh={};z(mh,{remoteStepServiceSocketIO:()=>rE});var Cu,rE,fh=E(()=>{"use strict";Au();Cu=class extends xs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},rE=new Cu});var gh={};z(gh,{remoteStepService:()=>As});var Pu,Gn,ku,As,jo=E(()=>{"use strict";Uo();ae();de();({REMOTE_STEP_SAVED:Pu}=Pt),ku=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Gn=(await Promise.resolve().then(()=>(fh(),mh))).remoteStepServiceSocketIO,Gn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:remoteStep`,{resultId:e},[Pu]):Gn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:remoteStep`,[Pu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Gn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(vt.removeFilter(`${e}:remoteStep`,[Pu]),Promise.resolve()):Gn.unlistenToRemoteStep(e)}},As=new ku});var Ou,Lr,hh=E(()=>{"use strict";Au();Ou=class extends xs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Lr=new Ou});var bh={};z(bh,{testResultService:()=>Dt});var yh,_u,Dt,$o=E(()=>{"use strict";yh=require("events");Uo();ae();de();hh();_u=class extends yh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){vt.onConnect=()=>this.emit("socket-connected");return}Lr.init(e),Lr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Pt.TEST_RESULT_UPDATED,Pt.TEST_RESULT_CREATED]):Lr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){vt.removeFilter(`${e}:testResult`,[Pt.TEST_RESULT_UPDATED,Pt.TEST_RESULT_CREATED]);return}await Lr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:testResult`,[Pt.TEST_RESULT_UPDATED,Pt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Lr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Lr.getSocket()}},Dt=new _u});var wh,vh,Sh,Ee,sE,Eh,Th,nE,Wo,Ih=E(()=>{"use strict";wh=I(require("lodash"));B();oe();$e();us();ct();ge();ah();vh=I(require("p-retry")),Sh=require("node:url");$();Fo();ys();ae();jo();$o();ge();Ee=P("test-run-handler"),sE=3,Eh=20*1e3,Th=s=>JSON.stringify(s).length<Eh,nE="Test couldn't be started",Wo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new xr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?rn(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get nativeApp(){return this._nativeApp}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return tn(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Qr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Oi.FROM_DEVICE:Oi.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 Vn({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await Ot(),refreshToken:Yi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Ld(),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 Qi()};if(this._options.disableMockNetwork&&bt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Th(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,c=this.testId;o?(Object.assign(t,{runData:i}),Ee.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Ee.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Eh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let i=await Wn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Ee.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testOptimization(){return this._testOptimization}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Th(e))return;let r=async()=>{try{return await Nu(this._options.project,this._testId,this._testResultId,e)}catch(o){return Ee.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Du(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===nE||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){F("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{F("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=o||{};F("before Runtime.evaluate"),await(0,vh.default)(async()=>{let{result:m}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!m.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),F("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 F("after Runtime.evaluate"),l.value}catch(o){throw Ee.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 Sh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){Ee.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(Ee.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:c,branch:l,_options:{project:m}}=this;try{let d=await Dr(a,c,m,l);n(d),r||setTimeout(o,3e3)}catch(d){Ee.error("failed to check if done",{err:d}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else Dt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Dr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Ee.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Ee.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ae.TEST_START_TIMEOUT_MSG)}catch(i){throw Ee.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Ae.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Dt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Ee.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Dt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Ee.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=wh.debounce(async()=>{try{await Dt.joinToTestResult(this._testResultId,this.testId)}catch(o){Ee.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Dr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Ee.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"?(Ee.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 Ee.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)Dt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Lu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Ee.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Ee.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Dt.off("socket-connected",e)}}listenToRemoteStep(e){As.listenToRemoteStep(this.testResultId,t=>{oh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:sE;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=re(),!((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 Vo,Rh=E(()=>{"use strict";Ih();Vo=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new Wo(e,t,c,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function Ah(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Uu({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 Mu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Fu(s,e){let t=s.mode===K.EXTENSION?Nr:Hn,r=xh.difference(Zs(s,e),t);if(r.length>0)throw bt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var xh,Nr,Hn,Go=E(()=>{"use strict";xh=I(require("lodash"));B();us();ge();Y();ae();Nr=["edge-chromium","chrome"],Hn=[...Nr,"firefox","safari","safari technology preview"]});var iE,oE,aE,qn,Bu=E(()=>{"use strict";cs();fs();$();iE=P("worker-utils"),oE=async(s,e,t)=>{e&&await vl(s,t)},aE=async(s,e,t)=>{await zl(s,e,t)},qn=async(s,e,t,r,n,i)=>{iE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await oE(s,e,t),n==="redis"&&await aE(s,r,t)}}});function pE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var qo,_h,zo,Ko,Lh,St,Ch,Ph,kh,Oh,Mr,cE,ju,lE,qt,uE,Ho,dE,Nt,zn=E(()=>{"use strict";qo=I(require("ms")),_h=I(require("lodash")),zo=I(require("p-retry")),Ko=I(require("dayjs")),Lh=I(require("dayjs/plugin/duration"));B();$e();cs();fs();ge();$();Bu();Lt();Po();de();jo();$o();ct();Ge();ae();Y();Ko.default.extend(Lh.default);St=P("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Ch,TEST_START_TIMEOUT_MSG:Ph,TEST_COMPLETE_TIMEOUT_MSG:kh,TEST_REACHED_CUSTOM_TIMEOUT_MSG:Oh}=Ae,{SETUP_TIMEOUT:Mr,NETWORK_ERROR:cE,GRID_ERROR:ju,BROWSER_CLOSED:lE,SELENIUM_ERROR:qt,UNKNOWN_ERROR:uE,MOBILE_SESSION_ERROR:Ho}=Xr;dE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Nt=class{constructor(e,t,r,n,i,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new 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 bf(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 Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new qs(!0)}async getBrowserOnce(e,t,r,n){throw new qs(!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(!Ye({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 n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Zr(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus: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=e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN,n=br(O.flags.appiumConnectionRequestTimeout.getValue(),(0,qo.default)("2m")),i=br(O.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===_.BROWSERSTACK||t&&r?o+(0,qo.default)("10m"):o+(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 n=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Ae.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,zo.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await le(Gf(o,a,this.id),this.options.getBrowserTimeout,Ae.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 i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{F("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);F("before getBrowserOnce retries");let c=this.options.getBrowserRetries-o;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,zo.default)(async()=>{let m=Date.now(),d=this.initPlayer(e);try{let u=await Tf(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,F("before getBrowserOnce");let f=await le(this.getBrowserOnce(e,t,d,u),this.getSessionTimeout(),Ae.GET_BROWSER_TIMEOUT_MSG);return F("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),d||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}),Q.onGetBrowserFailure(this.id,r,++l),d.onDone(),!(u instanceof At)&&this.options.mode!==K.APPIUM&&await pe(this.options.getBrowserTimeout-(Date.now()-m)),u}},{retries:c-1,minTimeout:0,factor:1}),F("after getBrowserOnce retries")}catch(o){throw await qn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[At,zr].some(a=>o instanceof a)?o:o instanceof st?new hr(o,ju):new hr(o,qt)}return n}async runTest(e,t,r){var m;F("inside runTest");let n=(m=this.userData)==null?void 0:m.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Zt(this.options)&&this.handleMobileTest(e);if(o)return o;F("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 Ot(),await this.runTestOnce(e,l)}finally{await qn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var L,M;if(Ye(g,this.options)||Zr(O,(L=this.options.gridData)==null?void 0:L.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let v=G=>y==null?void 0:y.message.includes(G),b=y&&y instanceof hr,w=v(Ph),S=y&&(v(kh)||w&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||w)&&e.retryOnInfraErrors,V=S&&e.hasMoreTimeoutRetries(),x=e.hasMoreRetries()&&!b&&!S,R=!g.success&&(x||V||D);try{let G=e.retryKey;g.testRetryKey=G;let W=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,R,W),await this.runTestCleanup(),R){if(V&&await e.startNewTimeoutRetry(),D){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 q=(M=this.options.projectData)==null?void 0:M.projectId,ie=e.testResultId,Ie=e.testId;await Jo(q,ie,Ie,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return x&&!D&&!V&&await e.startNewRetry(),St.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:S,testRetryKey:G,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(R)}t(this.id,...r);return}catch(G){if(G instanceof Xt)return;St.error("failed to process test result",{error:G}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
214
- Please make sure the CLI has stable access to the internet. ${Dc()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:v,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:w}=Wc,S=g instanceof Error?g.message:g;if(S.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),S.includes(Ch)||S.includes(b))return{errorType:Mr,reason:"timeout while getting device"};if(S.includes(Oh)){if(!this.testRunTimeout)return{errorType:Mr,reason:"Test timeout reached!"};let A=Ko.default.duration({milliseconds:this.testRunTimeout});return{errorType:Mr,reason:`Test timeout reached (timeout: ${zc(A)})`}}return S.includes(T)||S.includes(w)?{errorType:Ho,reason:"app doesn't exist on device"}:S.includes(v)?{errorType:Ho,reason:"app never started, check app permission or app activity"}:S.includes(y)?{errorType:Ho,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Ho,reason:S}},a=(g,y)=>{let T=this.options.mode===K.APPIUM?"device":"browser";if(!y&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:cE,reason:i()};let v=g instanceof Error?g.message:g;if(v.includes(Ch))return{errorType:Mr,reason:`Test couldn't get ${T}`};if(v.includes(Ph))return{errorType:Mr,reason:"Test couldn't be started"};if(v.includes(Oh)){if(!this.testRunTimeout)return{errorType:Mr,reason:"Test timeout reached: test is too long"};let b=Ko.default.duration({milliseconds:this.testRunTimeout}),w=Math.floor(b.asMinutes()),S=b.asSeconds(),A=w>0?` ${w} min`:"",D=S>0?` ${S} sec`:"";return{errorType:Mr,reason:`Test timeout reached (timeout:${A}${D}): test is too long`}}if(g instanceof hr&&g.type){if(g.type===ju)return{errorType:ju,reason:`Test couldn't get ${T} from grid - ${g.message}`};if(g.type===qt)return{errorType:qt,reason:`Failed to create new session - ${g.message}`}}return"type"in g&&g.type===lE?{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 ${T} you requested is supported in your plan`}:{errorType:uE,reason:v}},c=async g=>{var w;let y=await Lc();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),St.warn("error on run",{err:g});let T=(w=this.userData)==null?void 0:w.projectId,{errorType:v,reason:b}=this.options.mode===K.APPIUM?o(g):a(g,y);Jo(T,this.testResultId,this.testId,{status:Qs.COMPLETED,success:!1,reason:b,errorType:v,testRetryKey:e.retryKey,setupStepResult:{status:Qs.COMPLETED,success:!1,reason:b,errorType:v}},e.remoteRunId),await n(pE(this.testId,this.testName,this.testResultId,b),g)},l=async g=>{var w;let y=this.testId,T=this.testResultId,v=(w=this.userData)==null?void 0:w.projectId,b=this.branch;if(!y||!T||!v||!b)return St.warn("Test failed. Not enough data to recover results via API",{err:g}),c(g);try{let S=await Dr(y,T,v,b);if(St.warn("Test failed. Got results via API",{err:g,testResult:_h.default.omit(S,dE),resultId:T}),S&&S.status===Qs.COMPLETED&&!g.message.includes(kh))return await n(S);throw g}catch(S){return S!==g&&St.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:v,branch:b,err:S}),c(g)}},m=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===K.SELENIUM),d=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!d&&As.joinToRemoteStep(this.testResultId),!m&&Dt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==K.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),F("After onRunComplete"),t(this.id,...r)}catch(y){await l(y),t(this.id,...r)}finally{d||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 Nh,Dh,Cs,$u=E(()=>{"use strict";B();Nh=I(require("p-retry"));B();$();Y();Dh=P("window-utils"),Cs=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return Dh.warn("selenium navigation failed. retrying to navigate",{err:i}),await pe(1500),r(n-1);throw!i.seleniumStack&&o&&Dh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};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,n=document.documentElement,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await 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,Nh.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var Wu,Ps,Vu=E(()=>{"use strict";$();Wu=P("cookies-utils"),Ps=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,Xo,Mh=E(()=>{"use strict";Gu=I(require("p-retry")),Xo=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[i,o]=await(0,Gu.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,Gu.default)(i,{retries:t,minTimeout:r,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function Fh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let i=s.offset||{top:0,left:0};if(i.top*=r,i.left*=r,!s.elementRect)return mE.warn("missing elementRect",Bh.omit(s,"image")),{};let{elementRect:o}=s,a=await Yo.Jimp.fromBuffer(Buffer.from(n[1],"base64")),c=o.left*r+i.left*r,l=o.top*r+i.top*r,m=o.width*r,d=o.height*r;c<0&&(m+=c,m=Math.max(m,0),c=0),l<0&&(d+=l,d=Math.max(d,0),l=0);let u=a.bitmap.width,f=a.bitmap.height;if(c+m>u&&(m=u-c),l+d>f&&(d=f-l),d<=0||m<=0)throw new Hu("height or width is equal or lower than zero");return{elementImage:await a.crop({x:c,y:l,w:m,h:d}).getBase64(jh)}}async function fE(s,e){let t=new Yo.Jimp({width:s.width,height:s.height});for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await Yo.Jimp.fromBuffer(Buffer.from(i[1],"base64"));t.composite(o,n.position.left,n.position.top)}return await t.getBase64(jh)}function gE(s,e){return fE(s,e)}async function hE(){}async function yE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await hE(s[i]);return{key:i,url:o}}let r=await se(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function Uh(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 Bh,Yo,mE,jh,Hu,Qo,$h=E(()=>{"use strict";Bh=I(require("lodash"));B();Yo=require("jimp");$();mE=P("image-capture-utils"),jh="image/png",Hu=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Qo=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 Fh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Uh(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 yE({screenImage:t.image,absoluteScreenHighlight:Uh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>pe(250),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await Fh({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),T=f.height,v=Array.from({length:Math.ceil(h/g)},(w,S)=>({scrollX:Math.min(S*g,h-g),cropX:S*g-Math.min(S*g,h-g),cropW:g-(S*g-Math.min(S*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(w,S)=>({scrollY:Math.min(S*T,y-T),cropY:S*T-Math.min(S*T,y-T),cropH:T-(S*T-Math.min(S*T,y-T))}));return v.flatMap(w=>b.map(S=>({scrollPos:{x:w.scrollX,y:S.scrollY},cropData:{top:S.cropY,left:w.cropX,width:w.cropW,height:S.cropH}})))}async function l(u,f){let h=await t.getCurrentScrollPosition(),g=c(u,f),y=await a(g);return await t.scrollToPosition(h),gE(u,y)}let[m,d]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(m,d)}}});var Wh,Vh,Zo,ea,Gh=E(()=>{"use strict";Wh=I(require("p-retry")),Vh=I(require("semver"));B();$();$u();Mh();$h();we();Zo=P("tab-service"),ea=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Zo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=re();function c(l){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!l.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Cs(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Qo(t,a,new Xo(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=Z(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),c=n(o),l=n(a),m=r.map(d=>i.urlBreaker(d)).map(d=>n(d)).filter(d=>d===c);return c===l&&m.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Z();if(n){let l=this.getAllTabInfos(e),m=Object.keys(l).map(d=>l[d]);return n.isSameTab(m,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(l=>i[l].url);if(this.exactUrlMatch(t,r,o))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,o,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){Zo.error("failed to get url or title",{err:i})}}catch(n){Zo.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await 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]){Zo.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let i=await this.waitForTabToOpen(e);await this.addNewTab(e,i,this.pendingTabs[e]),this.addFrameHandler(i),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,Wh.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=Vh.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var c,l;let{tabMatcher:r,commonConstants:n}=Z();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((c=t.useCurrentTab)!=null&&c.call(t)){let m=await this.driver.getCurrentTabId();if(m)return m;let d=this.getMainTabId(e);if(d)return d;throw new Error("Current tab not found")}let i=(l=t.tabInfo)==null?void 0:l.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(m=>({...this.getTabInfo(e,m),tabId:m})).filter(m=>!m.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(m){let d=["no such window","no window found","the window could not be found"];if(m.message&&d.some(u=>m.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw m}}}});var qu,ta,zu=E(()=>{"use strict";qu=class{select(){return console.log(`
212
+ `,u=[],f=new th.Worker(d,{eval:!0});try{return await le(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};dt.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?dt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):dt.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",()=>{dt.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),i)}catch(h){if(!(h instanceof ce))throw h;return dt.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 VS(s){try{await Qg.promises.rm(s,{recursive:!0,force:!0})}catch(e){dt.warn("failed to remove install npm packages folder",{err:e})}}function rh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function Es(s,e,t,r,n,i){let o=rh(n,e,s,t),{data:a}=await GS(o,r,i);return a}async function Is(s,e,t,r,n,i,o,a,c,l){var g;let m=r.computePackagePathFromPackageJsonExports||O.flags.computePackagePathFromPackageJsonExports.isEnabled(),d=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(m){let T=Gm(y.testimPackageLocalLocation);return[y.paramName,Ss.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=rh(o,n,e,i);if(l){let y=await Ln(l);y&&(c=y)}Buffer.isBuffer(c)&&(dt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let f="data:,";return c==="data:"&&(dt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=f),{...await WS(u,t,r,s,d,a,c),nodeVersion:process.version}}async function GS(s,e,t){let r=e.map(l=>`${l.packageName}@${l.packageVersion}`),n=sh(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?n:Ss.join(n,`/${s}`),a=global.proxyUri;async function c(){let l="";try{if(l=await il(o,r,a,t),dt.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(d=>{let u=Wm(o,d.packageName);return{...d,packageFullName:`${d.packageName}@${u}`,packageLocalLocation:Ss.resolve(o,"node_modules",d.packageName)}}),installFolder:o}}catch(m){throw dt.warn("npm package install failed",{transactionId:s,err:m}),m}}try{return await le(c(),t)}catch(l){throw l instanceof ce&&dt.warn("timeout to install package",{packages:r,transactionId:s,err:l,timeout:t}),l}}function sh(){return Ss.join(Zg.tmpdir(),"/testim_local_packages")}function HS(){let s=sh();return VS(s)}var Qg,Zg,Ss,eh,th,dt,Rs=S(()=>{"use strict";Qg=I(require("fs")),Zg=I(require("os")),Ss=I(require("path"));B();os();eh=I(require("data-uri-to-buffer")),th=require("worker_threads");Y();W();ge();os();de();dt=P("cli-service");HS().catch(s=>dt.warn("failed to clean local package folder",{err:s}))});var ar={};z(ar,{run:()=>zS});function qS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var zS,nh=S(()=>{"use strict";Rs();Y();de();zS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:m,fileDataUrl:d,s3filepath:u}=e.data;try{let f=await Is(r,n,i,o,a,c,l,m,d,u);return f&&qS({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 Iu={};z(Iu,{run:()=>KS});var KS,ih=S(()=>{"use strict";Rs();Y();KS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await Es(t,r,n,o,i,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 ah(s,e,t,r){try{return await Ru(s,e,t,r)}catch{Uo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function XS(s,e,t,r,n){return Uo.info("finished to run remote step",{stepId:t,sessionId:n}),await ah(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function oh(s,e,t,r,n){return Uo.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await ah(s,e,t,{status:"completed",success:!1,failureReason:r})}async function ch(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),c=t.id;Uo.info("start play remote step",{stepType:o,stepId:c,sessionId:a});let l=JS[o];if(!l)return await oh(n,r,c,`Failed to find step type ${o}`,a);try{let m=await l.run(e,t,i);return await XS(n,r,c,m,a)}catch(m){return await oh(n,r,c,m.message,a)}}var Uo,JS,lh=S(()=>{"use strict";nh();ge();ih();W();Uo=P("step-playback"),JS={"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":ar,"cli-download-code-step":ar,"node-package":Iu}});var ph={};z(ph,{preloadTests:()=>Vn});async function Vn(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 se(s.testId,r=>Gn({...e,testId:r}),{concurrency:2});return uh.keyBy(t,"testData.id")},"loadTests",QS,[e,s.testId])()}var uh,QS,Bo=S(()=>{"use strict";uh=I(require("lodash"));er();ge();B();QS=1e3*60*60*10});var xu,dh,Lr,ZS,Au,St,jo=S(()=>{"use strict";B();ct();xu=I(require("ws")),dh=require("events");W();oe();Lr=P("socket-service"),ZS=5e3,Au=class extends dh.EventEmitter{constructor(){super(...arguments);this.clientId=re();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Lr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),ZS)}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(Cd);return _t().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new xu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return Lr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{Lr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===xu.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,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(c){n(c)&&i(c)}(Array.isArray(r)?r:[r]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=o.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=re(),c={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",l=>l.id===a,o),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},St=new Au});var fh,Cu,eE,tE,rE,mh,$o,xs,Pu=S(()=>{"use strict";fh=I(require("p-retry")),Cu=I(require("socket.io-client"));oe();B();W();eE=50,tE=10,rE=5e3,mh=10*1e3,$o=P("base socket service"),xs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);$o.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}$o.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===tE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=eE)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",()=>{$o.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:mh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${he()}/${t}`,this._socket=Cu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:mh,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=Cu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,fh.default)(()=>le(n(),rE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&$o.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var gh={};z(gh,{remoteStepServiceSocketIO:()=>sE});var ku,sE,hh=S(()=>{"use strict";Pu();ku=class extends xs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},sE=new ku});var yh={};z(yh,{remoteStepService:()=>As});var Ou,Hn,_u,As,Wo=S(()=>{"use strict";jo();ae();de();({REMOTE_STEP_SAVED:Ou}=kt),_u=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Hn=(await Promise.resolve().then(()=>(hh(),gh))).remoteStepServiceSocketIO,Hn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?St.addFilter(`${e}:remoteStep`,{resultId:e},[Ou]):Hn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){St.listenTo(`${e}:remoteStep`,[Ou],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Hn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(St.removeFilter(`${e}:remoteStep`,[Ou]),Promise.resolve()):Hn.unlistenToRemoteStep(e)}},As=new _u});var Lu,Dr,bh=S(()=>{"use strict";Pu();Lu=class extends xs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Dr=new Lu});var wh={};z(wh,{testResultService:()=>Nt});var Th,Du,Nt,Vo=S(()=>{"use strict";Th=require("events");jo();ae();de();bh();Du=class extends Th.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){St.onConnect=()=>this.emit("socket-connected");return}Dr.init(e),Dr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?St.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()){St.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()){St.listenTo(`${e}:testResult`,[kt.TEST_RESULT_UPDATED,kt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Dr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Dr.getSocket()}},Nt=new Du});var Sh,Eh,Ih,Ee,nE,Rh,vh,iE,Go,xh=S(()=>{"use strict";Sh=I(require("lodash"));B();oe();$e();us();ct();ge();lh();Eh=I(require("p-retry")),Ih=require("node:url");W();Bo();ys();ae();Wo();Vo();ge();Ee=P("test-run-handler"),nE=3,Rh=20*1e3,vh=s=>JSON.stringify(s).length<Rh,iE="Test couldn't be started",Go=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Ar;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?sn(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get nativeApp(){return this._nativeApp}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return rn(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Qr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?_i.FROM_DEVICE:_i.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 Gn({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await _t(),refreshToken:Zi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Nd(),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 eo()};if(this._options.disableMockNetwork&&Tt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=vh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,c=this.testId;o?(Object.assign(t,{runData:i}),Ee.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Ee.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Rh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let i=await Vn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Ee.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testOptimization(){return this._testOptimization}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&vh(e))return;let r=async()=>{try{return await Fu(this._options.project,this._testId,this._testResultId,e)}catch(o){return Ee.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Mu(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===iE||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){F("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{F("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=o||{};F("before Runtime.evaluate"),await(0,Eh.default)(async()=>{let{result:m}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!m.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),F("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 F("after Runtime.evaluate"),l.value}catch(o){throw Ee.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 Ih.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){Ee.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(Ee.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:c,branch:l,_options:{project:m}}=this;try{let d=await Nr(a,c,m,l);n(d),r||setTimeout(o,3e3)}catch(d){Ee.error("failed to check if done",{err:d}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else Nt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Nr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Ee.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Ee.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ae.TEST_START_TIMEOUT_MSG)}catch(i){throw Ee.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Ae.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)){Ee.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)){Ee.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Sh.debounce(async()=>{try{await Nt.joinToTestResult(this._testResultId,this.testId)}catch(o){Ee.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)?(Ee.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"?(Ee.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 Ee.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)Nt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Nu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Ee.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Ee.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=>{ch(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:nE;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=re(),!((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 Ho,Ah=S(()=>{"use strict";xh();Ho=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new Go(e,t,c,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function Ph(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await ju({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Uu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Bu(s,e){let t=s.mode===K.EXTENSION?Mr:qn,r=Ch.difference(en(s,e),t);if(r.length>0)throw Tt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Ch,Mr,qn,qo=S(()=>{"use strict";Ch=I(require("lodash"));B();us();ge();Y();ae();Mr=["edge-chromium","chrome"],qn=[...Mr,"firefox","safari","safari technology preview"]});var oE,aE,cE,zn,$u=S(()=>{"use strict";cs();fs();W();oE=P("worker-utils"),aE=async(s,e,t)=>{e&&await El(s,t)},cE=async(s,e,t)=>{await Jl(s,e,t)},zn=async(s,e,t,r,n,i)=>{oE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await aE(s,e,t),n==="redis"&&await cE(s,r,t)}}});function dE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Jo,_h,Xo,Yo,Lh,Et,kh,Oh,zo,Wu,Fr,lE,Vu,uE,zt,pE,Ko,mE,Mt,Kn=S(()=>{"use strict";Jo=I(require("ms")),_h=I(require("lodash")),Xo=I(require("p-retry")),Yo=I(require("dayjs")),Lh=I(require("dayjs/plugin/duration"));B();$e();cs();fs();ge();W();$u();Dt();Oo();de();Wo();Vo();ct();Ge();ae();Y();Yo.default.extend(Lh.default);Et=P("base-worker"),{GET_BROWSER_TIMEOUT_MSG:kh,TEST_START_TIMEOUT_MSG:Oh,TEST_COMPLETE_TIMEOUT_MSG:zo,TEST_REACHED_CUSTOM_TIMEOUT_MSG:Wu}=Ae,{SETUP_TIMEOUT:Fr,NETWORK_ERROR:lE,GRID_ERROR:Vu,BROWSER_CLOSED:uE,SELENIUM_ERROR:zt,UNKNOWN_ERROR:pE,MOBILE_SESSION_ERROR:Ko}=Xr;mE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Mt=class{constructor(e,t,r,n,i,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new 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 wf(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 Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new qs(!0)}async getBrowserOnce(e,t,r,n){throw new qs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),Et.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!Ye({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 n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Zr(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus: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=e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN,n=Tr(O.flags.appiumConnectionRequestTimeout.getValue(),(0,Jo.default)("2m")),i=Tr(O.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===_.BROWSERSTACK||t&&r?o+(0,Jo.default)("10m"):o+(0,Jo.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,Xo.default)(async()=>{let n=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Ae.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Xo.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await le(qf(o,a,this.id),this.options.getBrowserTimeout,Ae.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?Et.info("could not get grid slot due to concurrency issue",r):Et.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 i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{F("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);F("before getBrowserOnce retries");let c=this.options.getBrowserRetries-o;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,Xo.default)(async()=>{let m=Date.now(),d=this.initPlayer(e);try{let u=await vf(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,F("before getBrowserOnce");let f=await le(this.getBrowserOnce(e,t,d,u),this.getSessionTimeout(),Ae.GET_BROWSER_TIMEOUT_MSG);return F("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),d||f}catch(u){let f={...a,failedGetBrowserAttempts:l,id:this.options.gridData.gridId},h=this.options.mode===K.APPIUM?"device":"browser";throw Et.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++l),d.onDone(),!(u instanceof Ct)&&this.options.mode!==K.APPIUM&&await pe(this.options.getBrowserTimeout-(Date.now()-m)),u}},{retries:c-1,minTimeout:0,factor:1}),F("after getBrowserOnce retries")}catch(o){throw await zn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Ct,zr].some(a=>o instanceof a)?o:o instanceof st?new yr(o,Vu):new yr(o,zt)}return n}async runTest(e,t,r){var m;F("inside runTest");let n=(m=this.userData)==null?void 0:m.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Zt(this.options)&&this.handleMobileTest(e);if(o)return o;F("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 zn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var M,H;if(Ye(g,this.options)||Zr(O,(M=this.options.gridData)==null?void 0:M.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let w=j=>y==null?void 0:y.message.includes(j),b=y&&y instanceof yr,v=w(Oh),E=y&&(w(zo)||w(Wu)||v&&!e.retryOnInfraErrors),A=!!w(Wu)&&!!this.testRunTimeout,V=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||v)&&e.retryOnInfraErrors,x=E&&e.hasMoreTimeoutRetries()&&!A,R=e.hasMoreRetries()&&!b&&!E,L=!g.success&&(R||x||V);try{let j=e.retryKey;g.testRetryKey=j;let q=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,L,q),await this.runTestCleanup(),L){if(x&&await e.startNewTimeoutRetry(),V){Et.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 ie=(H=this.options.projectData)==null?void 0:H.projectId,Ie=e.testResultId,mt=e.testId;await Qo(ie,Ie,mt,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return R&&!V&&!x&&await e.startNewRetry(),Et.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:j,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(L)}t(this.id,...r);return}catch(j){if(j instanceof Xt)return;Et.error("failed to process test result",{error:j}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
214
+ Please make sure the CLI has stable access to the internet. ${Fc()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:w,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:v}=Hc,E=g instanceof Error?g.message:g;if(E.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),E.includes(kh)||E.includes(b))return{errorType:Fr,reason:"timeout while getting device"};if(E.includes(zo)||E.includes(Wu)){if(!this.testRunTimeout)return{errorType:Fr,reason:"Test timeout reached!"};let A=Yo.default.duration({milliseconds:this.testRunTimeout});return{errorType:Fr,reason:`Test timeout reached (timeout: ${Ni(A)})`}}return E.includes(T)||E.includes(v)?{errorType:Ko,reason:"app doesn't exist on device"}:E.includes(w)?{errorType:Ko,reason:"app never started, check app permission or app activity"}:E.includes(y)?{errorType:Ko,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Ko,reason:E}},a=(g,y)=>{let T=this.options.mode===K.APPIUM?"device":"browser";if(!y&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:lE,reason:i()};let w=g instanceof Error?g.message:g;if(w.includes(kh))return{errorType:Fr,reason:`Test couldn't get ${T}`};if(w.includes(Oh))return{errorType:Fr,reason:"Test couldn't be started"};if(g instanceof yr&&g.type){if(g.type===Vu)return{errorType:Vu,reason:`Test couldn't get ${T} from grid - ${g.message}`};if(g.type===zt)return{errorType:zt,reason:`Failed to create new session - ${g.message}`}}return w.includes(zo)?this.testRunTimeout?{errorType:Fr,reason:`Test timeout reached (timeout: ${Ni(Yo.default.duration({milliseconds:this.testRunTimeout}))})`}:{errorType:Fr,reason:"Test timeout reached: test is too long"}:"type"in g&&g.type===uE?{errorType:zt,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:zt,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:zt,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:zt,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:zt,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:zt,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:pE,reason:w}},c=async g=>{var v;let y=await Mc();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),Et.warn("error on run",{err:g});let T=(v=this.userData)==null?void 0:v.projectId,{errorType:w,reason:b}=this.options.mode===K.APPIUM?o(g):a(g,y);Qo(T,this.testResultId,this.testId,{status:Qs.COMPLETED,success:!1,reason:b,errorType:w,testRetryKey:e.retryKey,setupStepResult:{status:Qs.COMPLETED,success:!1,reason:b,errorType:w}},e.remoteRunId),await n(dE(this.testId,this.testName,this.testResultId,b),g)},l=async g=>{var v;let y=this.testId,T=this.testResultId,w=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!T||!w||!b)return Et.warn("Test failed. Not enough data to recover results via API",{err:g}),c(g);try{let E=await Nr(y,T,w,b);if(Et.warn("Test failed. Got results via API",{err:g,testResult:_h.default.omit(E,mE),resultId:T}),E&&E.status===Qs.COMPLETED&&!g.message.includes(zo))return await n(E);throw g}catch(E){return E!==g&&Et.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:w,branch:b,err:E}),c(g)}},m=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===K.SELENIUM),d=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!d&&As.joinToRemoteStep(this.testResultId),!m&&Nt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==K.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),F("After onRunComplete"),t(this.id,...r)}catch(y){await l(y),t(this.id,...r)}finally{d||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 Nh,Dh,Cs,Gu=S(()=>{"use strict";B();Nh=I(require("p-retry"));B();W();Y();Dh=P("window-utils"),Cs=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return Dh.warn("selenium navigation failed. retrying to navigate",{err:i}),await pe(1500),r(n-1);throw!i.seleniumStack&&o&&Dh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};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,n=document.documentElement,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await 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,Nh.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var Hu,Ps,qu=S(()=>{"use strict";W();Hu=P("cookies-utils"),Ps=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 Hu.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw Hu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw Hu.error("failed to remove cookie",{err:t}),t}}}});var zu,Zo,Mh=S(()=>{"use strict";zu=I(require("p-retry")),Zo=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[i,o]=await(0,zu.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,zu.default)(i,{retries:t,minTimeout:r,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function Fh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let i=s.offset||{top:0,left:0};if(i.top*=r,i.left*=r,!s.elementRect)return fE.warn("missing elementRect",Bh.omit(s,"image")),{};let{elementRect:o}=s,a=await ea.Jimp.fromBuffer(Buffer.from(n[1],"base64")),c=o.left*r+i.left*r,l=o.top*r+i.top*r,m=o.width*r,d=o.height*r;c<0&&(m+=c,m=Math.max(m,0),c=0),l<0&&(d+=l,d=Math.max(d,0),l=0);let u=a.bitmap.width,f=a.bitmap.height;if(c+m>u&&(m=u-c),l+d>f&&(d=f-l),d<=0||m<=0)throw new Ku("height or width is equal or lower than zero");return{elementImage:await a.crop({x:c,y:l,w:m,h:d}).getBase64(jh)}}async function gE(s,e){let t=new ea.Jimp({width:s.width,height:s.height});for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await ea.Jimp.fromBuffer(Buffer.from(i[1],"base64"));t.composite(o,n.position.left,n.position.top)}return await t.getBase64(jh)}function hE(s,e){return gE(s,e)}async function yE(){}async function bE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await yE(s[i]);return{key:i,url:o}}let r=await se(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function Uh(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 Bh,ea,fE,jh,Ku,ta,$h=S(()=>{"use strict";Bh=I(require("lodash"));B();ea=require("jimp");W();fE=P("image-capture-utils"),jh="image/png",Ku=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};ta=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 Fh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Uh(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 bE({screenImage:t.image,absoluteScreenHighlight:Uh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>pe(250),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await Fh({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),T=f.height,w=Array.from({length:Math.ceil(h/g)},(v,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))})),b=Array.from({length:Math.ceil(y/T)},(v,E)=>({scrollY:Math.min(E*T,y-T),cropY:E*T-Math.min(E*T,y-T),cropH:T-(E*T-Math.min(E*T,y-T))}));return w.flatMap(v=>b.map(E=>({scrollPos:{x:v.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:v.cropX,width:v.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),hE(u,y)}let[m,d]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(m,d)}}});var Wh,Vh,ra,sa,Gh=S(()=>{"use strict";Wh=I(require("p-retry")),Vh=I(require("semver"));B();W();Gu();Mh();$h();we();ra=P("tab-service"),sa=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),ra.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=re();function c(l){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!l.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Cs(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new ta(t,a,new Zo(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=Z(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),c=n(o),l=n(a),m=r.map(d=>i.urlBreaker(d)).map(d=>n(d)).filter(d=>d===c);return c===l&&m.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Z();if(n){let l=this.getAllTabInfos(e),m=Object.keys(l).map(d=>l[d]);return n.isSameTab(m,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(l=>i[l].url);if(this.exactUrlMatch(t,r,o))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,o,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){ra.error("failed to get url or title",{err:i})}}catch(n){ra.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await 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]){ra.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let i=await this.waitForTabToOpen(e);await this.addNewTab(e,i,this.pendingTabs[e]),this.addFrameHandler(i),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,Wh.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=Vh.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var c,l;let{tabMatcher:r,commonConstants:n}=Z();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((c=t.useCurrentTab)!=null&&c.call(t)){let m=await this.driver.getCurrentTabId();if(m)return m;let d=this.getMainTabId(e);if(d)return d;throw new Error("Current tab not found")}let i=(l=t.tabInfo)==null?void 0:l.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(m=>({...this.getTabInfo(e,m),tabId:m})).filter(m=>!m.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(m){let d=["no such window","no window found","the window could not be found"];if(m.message&&d.some(u=>m.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw m}}}});var Ju,na,Xu=S(()=>{"use strict";Ju=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(){}},ta=new qu});var Kn,ra,sa=E(()=>{"use strict";Vu();B();we();Kn={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"},ra=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=sn;this.getLinksFromUnescapeHTML=nn;this.cookieUtils=new Ps(this.driver)}get sessionPlayerInit(){return Z()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,i=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-i.x,y:e.y-i.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function qh(s){class e{constructor(r,n){this.frameManager=r;this.LocateElementPlayer=n;this._cache={}}cacheResults(r,n){this._cache[r]=n}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let n=Hh(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,i){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:c}=Z();if(c.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw bE.error(u),new Error(u)}let l=await s.switchToLocatedFrame(a),m=Hh(l.value),d=this.getResultsFromCache(m);return{url:"",frameId:-1,frameOffset:o,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:l.value,frameLocateResultUrl:d}}async locate(r,n,i,o,a,c){let l=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${n}`;let m=await l.locate(r,i,r.targetId);m.isVisible=!0;let d=await l.handleLocateResult(m,c,r).catch(()=>{throw new Error("")}),{locatedElement:u}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};d.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},l.addFrameDataToContext&&l.addFrameDataToContext(d.targetId,d.locateResult);let g=await this.foundFrameCallback(d,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,i,o){let a=O.flags.enableFrameSwitchOptimization.isEnabled(),l=i.playback.resultsHandler.resultsByChronologicOrder.at(-1),m=1,d=l&&l.stepId===r.id&&l.results.length>m;if(a&&!d&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),v=0;for(let b of T)v++,this.currentFrameHandler=await this.locate(b,v,this.currentFrameHandler,i,o,r);return this.currentFrameHandler}}let u=await o.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,i,o,r);return g}}return e}var bE,TE,Hh,zh=E(()=>{"use strict";$();de();we();Hr();bE=P("frame-locator"),TE="ELEMENT",Hh=s=>s?s[TE]||s[Jt]:null});var na,Ku=E(()=>{"use strict";oe();na=()=>{try{if(Rd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var H,me=E(()=>{"use strict";we();H=class{constructor(e,t,r,n={},i=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=i;this.locateElementPlayer=o;this.exportsTest=a;this.frameId=0}get driver(){var e;return(e=this.context.project.defaults)!=null&&e.ignoreVisibilityForExisting&&!this.stepActionUtils.driver.getIgnoreVisibility()&&this.stepActionUtils.driver.setIgnoreVisibility(!0),this.stepActionUtils.driver}get sessionPlayerInit(){return Z()}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 vE(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 SE(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t){let n=new Kh.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,i,o,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:m,positionUtils:d}=Z();if(vE(n,m,d,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=[d.calculateElementMiddlePoint(r),d.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(S){throw Fr.error("failed to execute getVisibilityCode",{err:S}),S}let{value:T}=y||{},v=T.elementVisibilityInfo||wE,[b,w]=T.elementsFromPointResults||[null,null];return m.checkElementVisibility(v,n,w,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=Z();await s.execute(r(t))}}}var Kh,Fr,wE,Jn,Jh=E(()=>{"use strict";me();$();de();we();Kh=require("linkedom"),Fr=P("locate-step-action"),wE={opacity:1,clientRects:{}};Jn=class extends H{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return SE(e)}static getFrameIdByTestimFrameId(){throw Fr.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw Fr.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw Fr.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw Fr.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw Fr.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw Fr.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Xh={};z(Xh,{scroll:()=>EE});var EE,Yh=E(()=>{"use strict";EE=function(s,e,t,r,n,i,o,a){function c(v,b){if(!b)return{success:!1};elementScrollTo(b,v.x,v.y);let w=b.scrollLeft,S=b.scrollTop;return{success:Math.abs(S-v.y)<1&&Math.abs(w-v.x)<1,actualX:w,actualY:S}}function l(v,b){if(!t)return{x:n,y:i};let w=getLocatedElement(b);if(r&&!w)return{x:v.scrollWidth,y:v.scrollHeight};if(!w)throw new Error("could not find target element");let S=w.getBoundingClientRect(),A=0,D=0,V=Math.max(window.innerHeight-(S.height+10),0),x=Math.max(window.innerWidth-(S.width+10),0);return A=a?v.scrollTop+S.top-Math.min(i,V):v.scrollTop,D=o?v.scrollLeft+S.left-Math.min(n,x):v.scrollLeft,{x:Math.round(D),y:Math.round(A)}}let m=!s,d=m?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!d)throw new Error("could not find target to scroll on");let u={top:d.scrollTop,left:d.scrollLeft},f=l(d,e),h=c(f,d);m&&!document.scrollingElement&&!h.success&&u.top===d.scrollTop&&u.left===d.scrollLeft&&(d=document.body,f=l(d,e),h=c(f,d));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let v=T.getBoundingClientRect();g=v.left,y=v.top}return{success:h.success,actualX:g,actualY:y}}});var ia,Qh=E(()=>{"use strict";me();ia=class extends H{getFailureString(e,t,r,n,i){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${i}, x: ${n})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${i}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${n}`),o}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:i}}=this.sessionPlayerInit,o=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),c=this.driver.isFirefox()?function(d,u,f){d.scrollTo(u,f)}:function(d,u,f){d.scrollTop=f,d.scrollLeft=u},{scroll:l}=await Promise.resolve().then(()=>(Yh(),Xh)),m=`
217
+ `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},na=new Ju});var Jn,ia,oa=S(()=>{"use strict";qu();B();we();Jn={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"},ia=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=nn;this.getLinksFromUnescapeHTML=on;this.cookieUtils=new Ps(this.driver)}get sessionPlayerInit(){return Z()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,i=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-i.x,y:e.y-i.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function qh(s){class e{constructor(r,n){this.frameManager=r;this.LocateElementPlayer=n;this._cache={}}cacheResults(r,n){this._cache[r]=n}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let n=Hh(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,i){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:c}=Z();if(c.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw TE.error(u),new Error(u)}let l=await s.switchToLocatedFrame(a),m=Hh(l.value),d=this.getResultsFromCache(m);return{url:"",frameId:-1,frameOffset:o,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:l.value,frameLocateResultUrl:d}}async locate(r,n,i,o,a,c){let l=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${n}`;let m=await l.locate(r,i,r.targetId);m.isVisible=!0;let d=await l.handleLocateResult(m,c,r).catch(()=>{throw new Error("")}),{locatedElement:u}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};d.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},l.addFrameDataToContext&&l.addFrameDataToContext(d.targetId,d.locateResult);let g=await this.foundFrameCallback(d,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,i,o){let a=O.flags.enableFrameSwitchOptimization.isEnabled(),l=i.playback.resultsHandler.resultsByChronologicOrder.at(-1),m=1,d=l&&l.stepId===r.id&&l.results.length>m;if(a&&!d&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),w=0;for(let b of T)w++,this.currentFrameHandler=await this.locate(b,w,this.currentFrameHandler,i,o,r);return this.currentFrameHandler}}let u=await o.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,i,o,r);return g}}return e}var TE,wE,Hh,zh=S(()=>{"use strict";W();de();we();Hr();TE=P("frame-locator"),wE="ELEMENT",Hh=s=>s?s[wE]||s[Jt]:null});var aa,Yu=S(()=>{"use strict";oe();aa=()=>{try{if(Ad)return!1;if(require("inspector").url())return!0}catch{}return!1}});var G,me=S(()=>{"use strict";we();G=class{constructor(e,t,r,n={},i=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=i;this.locateElementPlayer=o;this.exportsTest=a;this.frameId=0}get driver(){var e;return(e=this.context.project.defaults)!=null&&e.ignoreVisibilityForExisting&&!this.stepActionUtils.driver.getIgnoreVisibility()&&this.stepActionUtils.driver.setIgnoreVisibility(!0),this.stepActionUtils.driver}get sessionPlayerInit(){return Z()}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 SE(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 EE(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t){let n=new Kh.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,i,o,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:m,positionUtils:d}=Z();if(SE(n,m,d,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=[d.calculateElementMiddlePoint(r),d.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(E){throw Ur.error("failed to execute getVisibilityCode",{err:E}),E}let{value:T}=y||{},w=T.elementVisibilityInfo||vE,[b,v]=T.elementsFromPointResults||[null,null];return m.checkElementVisibility(w,n,v,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=Z();await s.execute(r(t))}}}var Kh,Ur,vE,Xn,Jh=S(()=>{"use strict";me();W();de();we();Kh=require("linkedom"),Ur=P("locate-step-action"),vE={opacity:1,clientRects:{}};Xn=class extends G{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return EE(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 Xh={};z(Xh,{scroll:()=>IE});var IE,Yh=S(()=>{"use strict";IE=function(s,e,t,r,n,i,o,a){function c(w,b){if(!b)return{success:!1};elementScrollTo(b,w.x,w.y);let v=b.scrollLeft,E=b.scrollTop;return{success:Math.abs(E-w.y)<1&&Math.abs(v-w.x)<1,actualX:v,actualY:E}}function l(w,b){if(!t)return{x:n,y:i};let v=getLocatedElement(b);if(r&&!v)return{x:w.scrollWidth,y:w.scrollHeight};if(!v)throw new Error("could not find target element");let E=v.getBoundingClientRect(),A=0,D=0,V=Math.max(window.innerHeight-(E.height+10),0),x=Math.max(window.innerWidth-(E.width+10),0);return A=a?w.scrollTop+E.top-Math.min(i,V):w.scrollTop,D=o?w.scrollLeft+E.left-Math.min(n,x):w.scrollLeft,{x:Math.round(D),y:Math.round(A)}}let m=!s,d=m?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!d)throw new Error("could not find target to scroll on");let u={top:d.scrollTop,left:d.scrollLeft},f=l(d,e),h=c(f,d);m&&!document.scrollingElement&&!h.success&&u.top===d.scrollTop&&u.left===d.scrollLeft&&(d=document.body,f=l(d,e),h=c(f,d));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let w=T.getBoundingClientRect();g=w.left,y=w.top}return{success:h.success,actualX:g,actualY:y}}});var ca,Qh=S(()=>{"use strict";me();ca=class extends G{getFailureString(e,t,r,n,i){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${i}, x: ${n})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${i}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${n}`),o}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:i}}=this.sessionPlayerInit,o=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),c=this.driver.isFirefox()?function(d,u,f){d.scrollTo(u,f)}:function(d,u,f){d.scrollTop=f,d.scrollLeft=u},{scroll:l}=await Promise.resolve().then(()=>(Yh(),Xh)),m=`
218
218
  const getLocatedElement = ${n.getLocatedElementCode};
219
219
  const elementScrollTo = ${c.toString()};
220
220
  const scroll = ${l.toString()};
221
221
  return scroll.apply(null, arguments)
222
- `;try{let d=await this.driver.executeJS(m,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(d!=null&&d.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=d.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var Zh,ey=E(()=>{"use strict";Zh=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),i=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!i)throw new Error("to element not found");let o=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var ty,ry=E(()=>{"use strict";ty=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(R){e({status:"done",result:R,success:!0})}function a(R){R||={},e({status:"failed",result:R,success:!1,keep:!0})}function c(R){return R!=null&&R.toLowerCase?(R=R.toLowerCase(),R==="text"?"text/plain":R==="url"?"text/uri-list":R):R}function l(){try{return new DataTransfer}catch{return{data:{},setData(L,M){i[c(L)]=M},getData(L){return i[c(L)]}}}}let m=["drag","dragstart","dragend"],d=["pointerup","pointerdown","pointermove"],u=m.concat(["drop","dragenter","dragover"]);function f(R){let L=R;for(;L&&L!==document.documentElement;){if(L.draggable)return L;L=L.parentElement}return null}function h(R,L,M){let G=L.element,{dispatchDragEventsOnClosestDraggable:W}=M;if(m.includes(R.type)&&W){if(!G&&L.lastDraggedElement)return L.lastDraggedElement;let q=f(G);if(q)return L.lastDraggedElement=q,q}return G}function g(R,L,M){function G(It,Gr,k){return k>It&&k<Gr}let W=R.pointerPosition||{};if(L)return{x:W.originX||0,y:W.originY||0};let q=M.getBoundingClientRect(),ie=W.originX&&G(q.left,q.left+q.width,W.originX)?W.originX:q.left+q.width/2,Ie=W.originY&&G(q.top,q.top+q.height,W.originY)?W.originY:q.top+q.height/2;return{x:ie,y:Ie}}function y(R,L,M){let G=(L==null?void 0:L.modifiers)||{},W=g(R,M.isDrag,M.element),q=(L==null?void 0:L.button)||0,ie=R.event;return d.includes(ie)?v(ie,G,W.x,W.y,q):u.includes(ie)?w(ie,G,W.x,W.y):b(ie,G,W.x,W.y,q)}function T(R,L,M){return{screenX:0,screenY:0,clientX:L,clientY:M,ctrlKey:Boolean(R.ctrl),altKey:Boolean(R.alt),shiftKey:Boolean(R.shift),metaKey:Boolean(R.meta),bubbles:!0,cancelable:!0,composed:!0}}function v(R,L,M,G,W){if(n){let ie=T(L,M,G);return ie.pointerType="mouse",ie.isPrimary=!0,new window.PointerEvent(R,ie)}let q=document.createEvent("PointerEvent");return q.initPointerEvent(R,!0,!0,document.defaultView,1,0,0,M,G,Boolean(L.ctrl),Boolean(L.alt),Boolean(L.shift),Boolean(L.meta),W,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),q}function b(R,L,M,G,W){let q=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return q.initMouseEvent(R,!0,!0,document.defaultView,1,0,0,M,G,Boolean(L.ctrl),Boolean(L.alt),Boolean(L.shift),Boolean(L.meta),W,document.body?document.body.parentNode:document.documentElement),q}function w(R,L,M,G){if(R==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let ie=document.createEvent("CustomEvent");return ie.initCustomEvent(R,!0,!0,null),Object.assign(ie,{dataTransfer:window.TSTA.dataTransfer}),ie}let W=T(L,M,G),q=new window.DragEvent(R,W);return Object.defineProperties(q,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),q}function S(R,L,M){let G=h(R,L,M);G==null||G.dispatchEvent(R)}function A(R,L){function M(){return R.event==="click"&&L.isDrag&&!L.allEventsOnSameElement}return M()}function D(R,L,M){if(M){let G=Math.min(M.timeStamp-L.timeStamp,40);setTimeout(()=>{V(R)},G)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function V(R){let L,M=R.events[R.eventIndex],G=R.events[++R.eventIndex];try{R.element=getLocatedElement(M.locatedElement),L=y(M,s,R)}catch(W){return a(`exception in get event in drag step:${W.message}`)}if(A(M,R))return D(R,M,G);if(L)try{S(L,R,M)}catch(W){return a(`exception in executeEvent in drag step:${W.message}`)}else return a(`cannot execute event ${M.event}`);D(R,M,G)}let x={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{V(x)}catch(R){a(R)}},0)}});var sy={};z(sy,{doClick:()=>IE});var IE,ny=E(()=>{"use strict";IE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,w){var D;function S(V){function x(){return i(V).find(M=>[...M.classList||[]].includes("Select-control"))}function R(){let M=x();return M?M.querySelector("input"):null}let L=R();L==null||L.focus()}let A=(D=b.quirks)==null?void 0:D.isReactSelect;w.type==="mousedown"&&A&&S(b.element)}function n(b,w){var A;let S=(A=b.quirks)==null?void 0:A.isCKEditorFrame;w.type==="click"&&S&&document.body.focus()}function i(b){let w=[];for(;b!=null&&b.parentNode;)w.push(b),b=b.parentNode;return w}function o(b){let w={status:"done",result:b,success:!0,...v.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(w)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function c(b){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),b.dispatchEvent(w)}function l(b){let w={},S=b.getBoundingClientRect(),A=S.left+S.width/2,D=S.top+S.height/2,R=f("mousemove",w,A,D,0);b.dispatchEvent(R)}function m(b,w){function S(R,L,M){return M>R&&M<L}let A=b.pointerPosition||{},D=w.getBoundingClientRect(),V=A.originX&&S(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,x=A.originY&&S(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:V,y:x}}function d(b,w,S){return{screenX:0,screenY:0,clientX:w,clientY:S,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,w,S,A){if(!window.PointerEvent)return;let D=d(w,S,A);return D.pointerType="mouse",D.isPrimary=!0,new window.PointerEvent(b,D)}function f(b,w,S,A,D){let V=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return V.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,S,A,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),D,document.body?document.body.parentNode:document.documentElement),V}function h(b,w){let S=["pointerup","pointerdown","pointermove"],A=w.modifiers||{},D=m(b,w.element),V=w.button||0,x=b.event;return S.includes(x)?u(x,A,D.x,D.y):f(x,A,D.x,D.y,V)}function g(){var w;let b=document.activeElement;for(;(w=b.shadowRoot)!=null&&w.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(w=>{try{return h(w,b)}catch{return}}).filter(Boolean).forEach(w=>{b.element.dispatchEvent(w),r(b,w),n(b,w)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let v={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!v.element){a("element not found");return}c(v.element),l(v.element);try{y(v);let b=g(),w=v.quirks,S=w==null?void 0:w.isReactSelect,A=w==null?void 0:w.isCKEditorFrame;!S&&!A&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var iy={};z(iy,{doDragPath:()=>RE});var RE,oy=E(()=>{"use strict";RE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(b){e({status:"done",result:b,success:!0})}function o(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),b.dispatchEvent(w)}function c(b){let w={},S=b.getBoundingClientRect(),A=S.left+S.width/2,D=S.top+S.height/2,R=u("mousemove",w,A,D,0);b.dispatchEvent(R)}function l(b,w){function S(R,L,M){return M>R&&M<L}let A=b.pointerPosition||{};if(v.isDrag)return{x:A.originX||0,y:A.originY||0};let D=w.getBoundingClientRect(),V=A.originX&&S(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,x=A.originY&&S(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:V,y:x}}function m(b,w,S){return{screenX:0,screenY:0,clientX:w,clientY:S,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function d(b,w,S,A,D){if(r){let x=m(w,S,A);return x.pointerType="mouse",x.isPrimary=!0,new window.PointerEvent(b,x)}let V=document.createEvent("PointerEvent");return V.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,S,A,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),D,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),V}function u(b,w,S,A,D){let V=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return V.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,S,A,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),D,document.body?document.body.parentNode:document.documentElement),V}function f(b,w){let S=["pointerup","pointerdown","pointermove"],A=w.modifiers||{},D=l(b,w.element),V=w.button||0,x=b.event;return S.includes(x)?d(x,A,D.x,D.y,V):u(x,A,D.x,D.y,V)}function h(b,w){function S(){return b.event==="click"&&w.isDrag&&!w.allEventsOnSameElement}return S()}function g(b,w,S){try{let A=f(w.events[b],w);h(A,w)||w.element.dispatchEvent(A)}catch{}if(b+1===w.events.length)S();else{let A=Math.min(w.events[b+1].timeStamp-w.events[b].timeStamp,n);setTimeout(()=>{g(b+1,w,S)},A)}}function y(b,w){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w()})}let v={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(!v.element){o("element not found");return}a(v.element),c(v.element),y(v,()=>{i()})}});var Xn,oa,ay=E(()=>{"use strict";Xn=I(require("lodash"));me();ey();de();ry();oa=class extends H{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(ny(),sy)),Promise.resolve().then(()=>(Un(),Fn))]),l=`
222
+ `;try{let d=await this.driver.executeJS(m,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(d!=null&&d.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=d.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var Zh,ey=S(()=>{"use strict";Zh=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),i=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!i)throw new Error("to element not found");let o=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var ty,ry=S(()=>{"use strict";ty=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(R){e({status:"done",result:R,success:!0})}function a(R){R||={},e({status:"failed",result:R,success:!1,keep:!0})}function c(R){return R!=null&&R.toLowerCase?(R=R.toLowerCase(),R==="text"?"text/plain":R==="url"?"text/uri-list":R):R}function l(){try{return new DataTransfer}catch{return{data:{},setData(L,M){i[c(L)]=M},getData(L){return i[c(L)]}}}}let m=["drag","dragstart","dragend"],d=["pointerup","pointerdown","pointermove"],u=m.concat(["drop","dragenter","dragover"]);function f(R){let L=R;for(;L&&L!==document.documentElement;){if(L.draggable)return L;L=L.parentElement}return null}function h(R,L,M){let H=L.element,{dispatchDragEventsOnClosestDraggable:j}=M;if(m.includes(R.type)&&j){if(!H&&L.lastDraggedElement)return L.lastDraggedElement;let q=f(H);if(q)return L.lastDraggedElement=q,q}return H}function g(R,L,M){function H(mt,mr,k){return k>mt&&k<mr}let j=R.pointerPosition||{};if(L)return{x:j.originX||0,y:j.originY||0};let q=M.getBoundingClientRect(),ie=j.originX&&H(q.left,q.left+q.width,j.originX)?j.originX:q.left+q.width/2,Ie=j.originY&&H(q.top,q.top+q.height,j.originY)?j.originY:q.top+q.height/2;return{x:ie,y:Ie}}function y(R,L,M){let H=(L==null?void 0:L.modifiers)||{},j=g(R,M.isDrag,M.element),q=(L==null?void 0:L.button)||0,ie=R.event;return d.includes(ie)?w(ie,H,j.x,j.y,q):u.includes(ie)?v(ie,H,j.x,j.y):b(ie,H,j.x,j.y,q)}function T(R,L,M){return{screenX:0,screenY:0,clientX:L,clientY:M,ctrlKey:Boolean(R.ctrl),altKey:Boolean(R.alt),shiftKey:Boolean(R.shift),metaKey:Boolean(R.meta),bubbles:!0,cancelable:!0,composed:!0}}function w(R,L,M,H,j){if(n){let ie=T(L,M,H);return ie.pointerType="mouse",ie.isPrimary=!0,new window.PointerEvent(R,ie)}let q=document.createEvent("PointerEvent");return q.initPointerEvent(R,!0,!0,document.defaultView,1,0,0,M,H,Boolean(L.ctrl),Boolean(L.alt),Boolean(L.shift),Boolean(L.meta),j,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),q}function b(R,L,M,H,j){let q=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return q.initMouseEvent(R,!0,!0,document.defaultView,1,0,0,M,H,Boolean(L.ctrl),Boolean(L.alt),Boolean(L.shift),Boolean(L.meta),j,document.body?document.body.parentNode:document.documentElement),q}function v(R,L,M,H){if(R==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let ie=document.createEvent("CustomEvent");return ie.initCustomEvent(R,!0,!0,null),Object.assign(ie,{dataTransfer:window.TSTA.dataTransfer}),ie}let j=T(L,M,H),q=new window.DragEvent(R,j);return Object.defineProperties(q,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),q}function E(R,L,M){let H=h(R,L,M);H==null||H.dispatchEvent(R)}function A(R,L){function M(){return R.event==="click"&&L.isDrag&&!L.allEventsOnSameElement}return M()}function D(R,L,M){if(M){let H=Math.min(M.timeStamp-L.timeStamp,40);setTimeout(()=>{V(R)},H)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function V(R){let L,M=R.events[R.eventIndex],H=R.events[++R.eventIndex];try{R.element=getLocatedElement(M.locatedElement),L=y(M,s,R)}catch(j){return a(`exception in get event in drag step:${j.message}`)}if(A(M,R))return D(R,M,H);if(L)try{E(L,R,M)}catch(j){return a(`exception in executeEvent in drag step:${j.message}`)}else return a(`cannot execute event ${M.event}`);D(R,M,H)}let x={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{V(x)}catch(R){a(R)}},0)}});var sy={};z(sy,{doClick:()=>RE});var RE,ny=S(()=>{"use strict";RE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,v){var D;function E(V){function x(){return i(V).find(M=>[...M.classList||[]].includes("Select-control"))}function R(){let M=x();return M?M.querySelector("input"):null}let L=R();L==null||L.focus()}let A=(D=b.quirks)==null?void 0:D.isReactSelect;v.type==="mousedown"&&A&&E(b.element)}function n(b,v){var A;let E=(A=b.quirks)==null?void 0:A.isCKEditorFrame;v.type==="click"&&E&&document.body.focus()}function i(b){let v=[];for(;b!=null&&b.parentNode;)v.push(b),b=b.parentNode;return v}function o(b){let v={status:"done",result:b,success:!0,...w.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function c(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},E=b.getBoundingClientRect(),A=E.left+E.width/2,D=E.top+E.height/2,R=f("mousemove",v,A,D,0);b.dispatchEvent(R)}function m(b,v){function E(R,L,M){return M>R&&M<L}let A=b.pointerPosition||{},D=v.getBoundingClientRect(),V=A.originX&&E(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,x=A.originY&&E(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:V,y:x}}function d(b,v,E){return{screenX:0,screenY:0,clientX:v,clientY:E,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,v,E,A){if(!window.PointerEvent)return;let D=d(v,E,A);return D.pointerType="mouse",D.isPrimary=!0,new window.PointerEvent(b,D)}function f(b,v,E,A,D){let V=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return V.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),D,document.body?document.body.parentNode:document.documentElement),V}function h(b,v){let E=["pointerup","pointerdown","pointermove"],A=v.modifiers||{},D=m(b,v.element),V=v.button||0,x=b.event;return E.includes(x)?u(x,A,D.x,D.y):f(x,A,D.x,D.y,V)}function g(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return h(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),r(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let w={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!w.element){a("element not found");return}c(w.element),l(w.element);try{y(w);let b=g(),v=w.quirks,E=v==null?void 0:v.isReactSelect,A=v==null?void 0:v.isCKEditorFrame;!E&&!A&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var iy={};z(iy,{doDragPath:()=>xE});var xE,oy=S(()=>{"use strict";xE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(b){e({status:"done",result:b,success:!0})}function o(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},E=b.getBoundingClientRect(),A=E.left+E.width/2,D=E.top+E.height/2,R=u("mousemove",v,A,D,0);b.dispatchEvent(R)}function l(b,v){function E(R,L,M){return M>R&&M<L}let A=b.pointerPosition||{};if(w.isDrag)return{x:A.originX||0,y:A.originY||0};let D=v.getBoundingClientRect(),V=A.originX&&E(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,x=A.originY&&E(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:V,y:x}}function m(b,v,E){return{screenX:0,screenY:0,clientX:v,clientY:E,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function d(b,v,E,A,D){if(r){let x=m(v,E,A);return x.pointerType="mouse",x.isPrimary=!0,new window.PointerEvent(b,x)}let V=document.createEvent("PointerEvent");return V.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),D,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),V}function u(b,v,E,A,D){let V=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return V.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),D,document.body?document.body.parentNode:document.documentElement),V}function f(b,v){let E=["pointerup","pointerdown","pointermove"],A=v.modifiers||{},D=l(b,v.element),V=v.button||0,x=b.event;return E.includes(x)?d(x,A,D.x,D.y,V):u(x,A,D.x,D.y,V)}function h(b,v){function E(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return E()}function g(b,v,E){try{let A=f(v.events[b],v);h(A,v)||v.element.dispatchEvent(A)}catch{}if(b+1===v.events.length)E();else{let A=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{g(b+1,v,E)},A)}}function y(b,v){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let w={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(!w.element){o("element not found");return}a(w.element),c(w.element),y(w,()=>{i()})}});var Yn,la,ay=S(()=>{"use strict";Yn=I(require("lodash"));me();ey();de();ry();la=class extends G{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(ny(),sy)),Promise.resolve().then(()=>(Bn(),Un))]),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(m=(await this.driver.executeCodeAsync(l,n,o)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(d){return{success:!1,reason:d.message,exception:d}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var c;let e=(c=this.step.events[0])==null?void 0:c.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),i=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=n?0:r.left+r.width/2-e.originX,a=i?0:r.top+r.height/2-e.originY;return{xOffset:o,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=Xn.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:n}=this.step,i=e.find(l=>["mousedown","pointerdown"].includes(l.event));if(i){let l=e.indexOf(i);e.splice(l,0,this.generateEventOfType(i,"mouseover"))}let{recordPointerMoveEvents:o=!1}=this.context.project.defaults||{},a=e.find(l=>l.event==="mouseup")||o&&e.find(l=>l.event==="pointerup"),c=Number(Xn.findLastIndex(e,l=>l.event==="mousemove")||o&&Xn.findLastIndex(e,l=>l.event==="pointermove"));a&&c>0&&!t&&e.splice(c+1,0,this.generateEventOfType(a,"mouseover")),r&&!n&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var m,d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3;if(!((m=e.events)!=null&&m.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let i=e.events,o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(oy(),iy)),Promise.resolve().then(()=>(Un(),Fn))]),l=`
229
+ `;try{return(m=(await this.driver.executeCodeAsync(l,n,o)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(d){return{success:!1,reason:d.message,exception:d}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var c;let e=(c=this.step.events[0])==null?void 0:c.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),i=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=n?0:r.left+r.width/2-e.originX,a=i?0:r.top+r.height/2-e.originY;return{xOffset:o,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=Yn.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:n}=this.step,i=e.find(l=>["mousedown","pointerdown"].includes(l.event));if(i){let l=e.indexOf(i);e.splice(l,0,this.generateEventOfType(i,"mouseover"))}let{recordPointerMoveEvents:o=!1}=this.context.project.defaults||{},a=e.find(l=>l.event==="mouseup")||o&&e.find(l=>l.event==="pointerup"),c=Number(Yn.findLastIndex(e,l=>l.event==="mousemove")||o&&Yn.findLastIndex(e,l=>l.event==="pointermove"));a&&c>0&&!t&&e.splice(c+1,0,this.generateEventOfType(a,"mouseover")),r&&!n&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var m,d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3;if(!((m=e.events)!=null&&m.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let i=e.events,o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(oy(),iy)),Promise.resolve().then(()=>(Bn(),Un))]),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
- `;try{return(d=(await this.driver.executeCodeAsync(l,n,o)).value)!=null&&d.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:n,rect:i}=e,o={frameOffset:{x:i.left-n.left,y:i.top-n.top},rect:n,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n)};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 m={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,m,o)}if(this.step.isDrag){if(this.step.toElement){let m=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(),T={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},v=`
234
+ `;try{return(d=(await this.driver.executeCodeAsync(l,n,o)).value)!=null&&d.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:n,rect:i}=e,o={frameOffset:{x:i.left-n.left,y:i.top-n.top},rect:n,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n)};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 m={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,m,o)}if(this.step.isDrag){if(this.step.toElement){let m=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(),T={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},w=`
235
235
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
236
236
  var dnd = ${ty.toString()};
237
237
  var eventData = arguments[0];
238
238
  var done = arguments[1];
239
239
  return dnd.call(null, eventData, done);
240
- `;return this.driver.executeCodeAsync(v,g,T)}let u=`
240
+ `;return this.driver.executeCodeAsync(w,g,T)}let u=`
241
241
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
242
242
  var dnd = ${Zh.toString()};
243
243
  var eventData = arguments[0];
244
244
  return dnd.call(null, eventData);
245
- `,f={fromLocatedElement:t,toLocatedElement:m.locatedElement};return this.driver.executeJS(u,f)}let d=this.getDnDRectsAndOffsets(e,m,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,m.seleniumElement,d)}return this.dragPathJs()}let c=this.driver.isSafari()&&this.step.button===2,l=this.driver.isSafari()&&e.tagName==="SELECT";return l?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!l&&(!this.step.nativeEvents||c)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=i=>i.fireOnTarget||["drop","dragenter"].includes(i.event);return e.forEach(i=>Object.assign(i,{locatedElement:n(i)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var Yn,cy=E(()=>{"use strict";me();Yn=class extends H{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:i}}=this,o=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(o),{evaluatedText:c}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var ly,xE,aa,uy=E(()=>{"use strict";ly=I(require("lodash"));me();$();xE=P("evaluate-expression-step-action"),aa=class extends H{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{xE.info("runner running incoming params evaluation");let i=t.incomingParams||{};ly.isEmpty(i)&&(i=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let o=["context",...i.as.functionParameters],a=[t,...i.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),d=Function.apply(Function,o.concat([l]))(...a);return t.data[e.targetName]=d,t.data[e.targetId]=d,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:d,data:t.data}}catch(i){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:i.toString()},success:!1}}}}});var py={};z(py,{setText:()=>AE});var AE,dy=E(()=>{"use strict";AE=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){Ie()},window.addEventListener("unload",window.__unloadNavigator);let i=new Set(["keydown","keyup","keypress"]),o=15;function a(k){try{if(!t)return;let N=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return k.eventData&&(N.data=k.eventData.data),N}catch{}}function c(k){try{let N=document.createEvent("TextEvent");N.data=k.eventData.data;let j=1,J=k.eventData.locale||"en-US";return N.initTextEvent("textInput",!0,!0,window,k.eventData.data,j,J),N}catch{}}function l(k){return a(k)||c(k)}function m(k,N,j){try{return new KeyboardEvent(k,{bubbles:!0,cancelable:!0,location:N.location||0,key:N.key||"",ctrlKey:Boolean(j.ctrl),shiftKey:Boolean(j.shift),altKey:Boolean(j.alt),metaKey:Boolean(j.meta)})}catch{}}function d(k,N,j){try{let J=document.createEvent("KeyboardEvent");return J.initKeyEvent(k,!0,!0,null,Boolean(j.ctrl),Boolean(j.alt),Boolean(j.shift),Boolean(j.meta),N.key||"",0),J}catch{}}function u(k,N,j){try{let J=document.createEvent("Events");return J.initEvent(k,!0,!0),Object.assign(J,{altKey:Boolean(j.alt),ctrlKey:Boolean(j.ctrl),metaKey:Boolean(j.meta),shiftKey:Boolean(j.shift),keyCode:N.key||""}),J}catch{}}function f(k,N,j){return m(k,N,j)||d(k,N,j)||u(k,N,j)}function h(k){if(!i.has(k.event))return null;let N=k.eventData,j=N.modifiers||{},J=f(k.event,N,j);return Object.defineProperties(J,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(J,{_keyCode_:N.keyCode,_charCode_:N.charCode||0}),J}function g(k){return k.event==="textInput"?l(k):h(k)}function y(k,N){return(()=>{var J;return k.event==="textInput"&&!((J=N.quirks)!=null&&J.isAuth0Form)})()}function T(k,N){return k.event==="keyup"&&N.event==="keydown"?o:0}function v(k,N){let j=T(k,N);return Math.min(N.timeStamp-k.timeStamp,j)}function b(k){let N=Object.getOwnPropertyDescriptor(k,"value");if(!N)return;let j=k.value;k.value=`${j}#`,N.configurable&&delete k.value,k.value=j;let J=document.createEvent("HTMLEvents");J.initEvent("input",!0,!1),k.dispatchEvent(J),Object.defineProperty(k,"value",N)}function w(k){if(G(k.element))try{if(b(k.element),t)k.element.dispatchEvent(new Event("change"));else{let N=document.createEvent("HTMLEvents");N.initEvent("change",!1,!0),k.element.dispatchEvent(N)}}catch{}}function S(k,N,j){j?setTimeout(()=>{M(k)},v(N,j)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w(k),Ie())}function A(k,N){return(k==="change"||k==="blur")&&N.element.tagName==="OPTION"}function D(k,N,j){return A(k.type,N)?N.element.parentElement:j.locatedElement?getLocatedElement(j.locatedElement):N.element}function V(k,N){let j=k.firstChild,J;for(;j;){if(j.nodeType===3){if(N.offset--<=0)return j}else if(j.nodeType===1&&(J=V(j,N),J))return J;j=j.nextSibling}return null}function x(k,N){if(!(!k||!N)){if(!isNaN(N.start))Object.assign(k,{selectionStart:N.start,selectionEnd:N.end});else if(!isNaN(N.nodeOffset)){let j;if(k.firstChild?j=V(k,{offset:N.nodeOffset}):j=k,j){let J=window.getSelection(),_e=document.createRange();try{J.removeAllRanges(),_e.setStart(j,N.textOffset),_e.setEnd(j,N.textOffset),J.addRange(_e)}catch{}}}}}function R(k,N){return k==="submit"&&Boolean(N.action)}function L(k,N,j){if(N.isFocusable&&N.isSelectable(k)&&k.type!=="submit")try{x(N.element,j.eventData.selection)}catch{}let J=D(k,N,j);if(!J)throw new Error("could not find element");R(k.type,J)?J.submit():J.dispatchEvent(k)}function M(k){let N,j=k.events[k.eventIndex],J=k.events[++k.eventIndex];try{N=g(j)}catch(_e){return It(`exception in get event in text step:${_e.message}`)}if(y(j,k))return S(k,j,J);if(N)try{L(N,k,j)}catch(_e){return It(`exception in executeEvent in text step:${_e.message}`)}else if(k.noEventExecuter)k.noEventExecuter(k,j);else return It(`cannot execute event ${j.event}`);S(k,j,J)}function G(k){let N=k.tagName;return N==="INPUT"||N==="TEXTAREA"}function W(k){return k.getAttribute?Boolean(k.getAttribute("contenteditable")==="true"):!1}function q(k,N){if(G(k.element)){k.element.value=N.eventData.text;let j=document.createEvent("Event");j.initEvent("input",!0,!1),k.element.dispatchEvent(j)}else k.isContentEditable&&(k.element.innerHTML=N.eventData.text)}function ie(){var N;let k=document.activeElement;for(;(N=k.shadowRoot)!=null&&N.activeElement;)k=k.shadowRoot.activeElement;return k}function Ie(k){let N={status:"done",result:k,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}function It(k){k||="";let N={status:"failed",result:k,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}try{let k=G(n.element);n.isContentEditable=W(n.element),!k&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=k||n.isContentEditable,n.isSelectable=N=>N.type!=="keyup",n.noEventExecuter=q}catch(k){It(`exception in set text step:${k.message}`);return}let Gr=ie();dispatchFocus(s.elementToFocusLocatedElement,Gr),M(n)}});var ca,my=E(()=>{"use strict";me();B();ca=class extends H{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Ne(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:i}=this,o=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:c}=i.codeSnippets;if(o.isDraftEditor&&c)return this.driver.executeJS(c(o.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let l={eventType:t,events:e,quirks:r,locatedElement:o.locatedElement,isRoot:o.isRoot,elementToFocusLocatedElement:o.elementToFocusLocatedElement},[{setText:m},{dispatchFocus:d}]=await Promise.all([Promise.resolve().then(()=>(dy(),py)),Promise.resolve().then(()=>(Un(),Fn))]),u=`
245
+ `,f={fromLocatedElement:t,toLocatedElement:m.locatedElement};return this.driver.executeJS(u,f)}let d=this.getDnDRectsAndOffsets(e,m,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,m.seleniumElement,d)}return this.dragPathJs()}let c=this.driver.isSafari()&&this.step.button===2,l=this.driver.isSafari()&&e.tagName==="SELECT";return l?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!l&&(!this.step.nativeEvents||c)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=i=>i.fireOnTarget||["drop","dragenter"].includes(i.event);return e.forEach(i=>Object.assign(i,{locatedElement:n(i)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var Qn,cy=S(()=>{"use strict";me();Qn=class extends G{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:i}}=this,o=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(o),{evaluatedText:c}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var ly,AE,ua,uy=S(()=>{"use strict";ly=I(require("lodash"));me();W();AE=P("evaluate-expression-step-action"),ua=class extends G{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{AE.info("runner running incoming params evaluation");let i=t.incomingParams||{};ly.isEmpty(i)&&(i=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let o=["context",...i.as.functionParameters],a=[t,...i.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),d=Function.apply(Function,o.concat([l]))(...a);return t.data[e.targetName]=d,t.data[e.targetId]=d,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:d,data:t.data}}catch(i){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:i.toString()},success:!1}}}}});var py={};z(py,{setText:()=>CE});var CE,dy=S(()=>{"use strict";CE=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){Ie()},window.addEventListener("unload",window.__unloadNavigator);let i=new Set(["keydown","keyup","keypress"]),o=15;function a(k){try{if(!t)return;let N=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return k.eventData&&(N.data=k.eventData.data),N}catch{}}function c(k){try{let N=document.createEvent("TextEvent");N.data=k.eventData.data;let $=1,J=k.eventData.locale||"en-US";return N.initTextEvent("textInput",!0,!0,window,k.eventData.data,$,J),N}catch{}}function l(k){return a(k)||c(k)}function m(k,N,$){try{return new KeyboardEvent(k,{bubbles:!0,cancelable:!0,location:N.location||0,key:N.key||"",ctrlKey:Boolean($.ctrl),shiftKey:Boolean($.shift),altKey:Boolean($.alt),metaKey:Boolean($.meta)})}catch{}}function d(k,N,$){try{let J=document.createEvent("KeyboardEvent");return J.initKeyEvent(k,!0,!0,null,Boolean($.ctrl),Boolean($.alt),Boolean($.shift),Boolean($.meta),N.key||"",0),J}catch{}}function u(k,N,$){try{let J=document.createEvent("Events");return J.initEvent(k,!0,!0),Object.assign(J,{altKey:Boolean($.alt),ctrlKey:Boolean($.ctrl),metaKey:Boolean($.meta),shiftKey:Boolean($.shift),keyCode:N.key||""}),J}catch{}}function f(k,N,$){return m(k,N,$)||d(k,N,$)||u(k,N,$)}function h(k){if(!i.has(k.event))return null;let N=k.eventData,$=N.modifiers||{},J=f(k.event,N,$);return Object.defineProperties(J,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(J,{_keyCode_:N.keyCode,_charCode_:N.charCode||0}),J}function g(k){return k.event==="textInput"?l(k):h(k)}function y(k,N){return(()=>{var J;return k.event==="textInput"&&!((J=N.quirks)!=null&&J.isAuth0Form)})()}function T(k,N){return k.event==="keyup"&&N.event==="keydown"?o:0}function w(k,N){let $=T(k,N);return Math.min(N.timeStamp-k.timeStamp,$)}function b(k){let N=Object.getOwnPropertyDescriptor(k,"value");if(!N)return;let $=k.value;k.value=`${$}#`,N.configurable&&delete k.value,k.value=$;let J=document.createEvent("HTMLEvents");J.initEvent("input",!0,!1),k.dispatchEvent(J),Object.defineProperty(k,"value",N)}function v(k){if(H(k.element))try{if(b(k.element),t)k.element.dispatchEvent(new Event("change"));else{let N=document.createEvent("HTMLEvents");N.initEvent("change",!1,!0),k.element.dispatchEvent(N)}}catch{}}function E(k,N,$){$?setTimeout(()=>{M(k)},w(N,$)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(k),Ie())}function A(k,N){return(k==="change"||k==="blur")&&N.element.tagName==="OPTION"}function D(k,N,$){return A(k.type,N)?N.element.parentElement:$.locatedElement?getLocatedElement($.locatedElement):N.element}function V(k,N){let $=k.firstChild,J;for(;$;){if($.nodeType===3){if(N.offset--<=0)return $}else if($.nodeType===1&&(J=V($,N),J))return J;$=$.nextSibling}return null}function x(k,N){if(!(!k||!N)){if(!isNaN(N.start))Object.assign(k,{selectionStart:N.start,selectionEnd:N.end});else if(!isNaN(N.nodeOffset)){let $;if(k.firstChild?$=V(k,{offset:N.nodeOffset}):$=k,$){let J=window.getSelection(),_e=document.createRange();try{J.removeAllRanges(),_e.setStart($,N.textOffset),_e.setEnd($,N.textOffset),J.addRange(_e)}catch{}}}}}function R(k,N){return k==="submit"&&Boolean(N.action)}function L(k,N,$){if(N.isFocusable&&N.isSelectable(k)&&k.type!=="submit")try{x(N.element,$.eventData.selection)}catch{}let J=D(k,N,$);if(!J)throw new Error("could not find element");R(k.type,J)?J.submit():J.dispatchEvent(k)}function M(k){let N,$=k.events[k.eventIndex],J=k.events[++k.eventIndex];try{N=g($)}catch(_e){return mt(`exception in get event in text step:${_e.message}`)}if(y($,k))return E(k,$,J);if(N)try{L(N,k,$)}catch(_e){return mt(`exception in executeEvent in text step:${_e.message}`)}else if(k.noEventExecuter)k.noEventExecuter(k,$);else return mt(`cannot execute event ${$.event}`);E(k,$,J)}function H(k){let N=k.tagName;return N==="INPUT"||N==="TEXTAREA"}function j(k){return k.getAttribute?Boolean(k.getAttribute("contenteditable")==="true"):!1}function q(k,N){if(H(k.element)){k.element.value=N.eventData.text;let $=document.createEvent("Event");$.initEvent("input",!0,!1),k.element.dispatchEvent($)}else k.isContentEditable&&(k.element.innerHTML=N.eventData.text)}function ie(){var N;let k=document.activeElement;for(;(N=k.shadowRoot)!=null&&N.activeElement;)k=k.shadowRoot.activeElement;return k}function Ie(k){let N={status:"done",result:k,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}function mt(k){k||="";let N={status:"failed",result:k,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}try{let k=H(n.element);n.isContentEditable=j(n.element),!k&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=k||n.isContentEditable,n.isSelectable=N=>N.type!=="keyup",n.noEventExecuter=q}catch(k){mt(`exception in set text step:${k.message}`);return}let mr=ie();dispatchFocus(s.elementToFocusLocatedElement,mr),M(n)}});var pa,my=S(()=>{"use strict";me();B();pa=class extends G{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Ne(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:i}=this,o=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:c}=i.codeSnippets;if(o.isDraftEditor&&c)return this.driver.executeJS(c(o.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let l={eventType:t,events:e,quirks:r,locatedElement:o.locatedElement,isRoot:o.isRoot,elementToFocusLocatedElement:o.elementToFocusLocatedElement},[{setText:m},{dispatchFocus:d}]=await Promise.all([Promise.resolve().then(()=>(dy(),py)),Promise.resolve().then(()=>(Bn(),Un))]),u=`
246
246
  var getLocatedElement = ${i.codeSnippets.getLocatedElementCode};
247
247
  var dispatchFocus = ${d};
248
248
  var setText = ${m.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(Ne(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(Ne(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 fy={};z(fy,{runCode:()=>CE});var CE,gy=E(()=>{"use strict";CE=function(s,e){var m;function t(d,u){let f=`data-testim-${d}`,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 T={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(T))}catch(y){let T=y.message.toLowerCase().includes("quota"),v=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||T||v){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let S={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(S)),T||v)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(d){return d.function?d.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):d.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(d.otherParams)}function n(d,u){function f(){return d.apply(null,u)}return f.prototype=d.prototype,new f}let i={},o={},a={},c=s.functionParams,l=s.transactionId;try{let d=r(s);d.push(i,o,a);let u=((m=s.function)==null?void 0:m.params)||c,h=(e||n(Function,u)).apply(null,d);typeof Promise<"u"&&h instanceof Promise?(t(l,{type:"promise"}),h.then(g=>{t(l,{status:"done",success:!0,result:{resultValue:g,exports:i,exportsTest:o,exportsGlobal:a}})},g=>{t(l,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:i,exportsTest:o,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:h,exports:i,exportsTest:o,exportsGlobal:a}})}catch(d){t(l,{status:"failed",success:!1,result:{resultValue:d.toString(),exports:i,exportsTest:o,exportsGlobal:a}})}}});var la,Qn,cr,ua=E(()=>{"use strict";la=I(require("lodash"));B();me();$();de();Qn=P("base-js-step-action"),cr=class extends H{isExceedingMaxResultSize(t,r){var n;try{let i=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,o=O.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>o;return i?a:(a&&Qn.warn(`js result size exceeded ${o}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let n=`data-testim-${r}`;try{return window.sessionStorage.getItem(n)}catch(i){if(i.message.includes("sessionStorage")||i.message.includes("The operation is insecure")){let o=document.head.querySelector("#testim-storage-backup");return o?o.getAttribute(n):"{}"}throw i}},t)}constructJSFunParams(t){let r=t.incomingParams,n=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],i=[t.context,...r.as.functionArguments];return n.push(t.code),i.forEach(o=>{la.isObject(o)&&Di(o,"seleniumElement",la.isEqual)}),{function:{params:n,args:i},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:n,step:{id:i=""}}=this,o=r.config.retryTimeout,a=r.data.timeToPlayStep-o,c=async()=>{let l;try{l=await this.executeGetStatus(t)}catch(u){Qn.warn("failed to get js status",{err:u}),l={value:'{ "status": "exception" }'}}let m;try{m=JSON.parse((l==null?void 0:l.value)||"{}")}catch{Qn.warn("non object value",{selRes:l}),m={status:"exception"}}let d=n.abortedSteps.find(u=>u.id===i);return d||(m?m.status==="done"?m:m.status==="failed"?{success:!1,shouldRetry:!0,result:m.result}:a-o<=0?Object.assign(m,{success:!1,shouldRetry:!0}):(a-=o,await pe(o),c()):{success:!0})};return c()}async executeInAut(t){let r=O.flags.experimentalPreCodeCompilation.isEnabled(),n=O.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(t),o=i.function.args.some(d=>Boolean(d==null?void 0:d.locatedElement)),a="undefined";if(r){let d=i.function.params.slice(0,-1);a=n?`async function(${d.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(Ne(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(Ne(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 fy={};z(fy,{runCode:()=>PE});var PE,gy=S(()=>{"use strict";PE=function(s,e){var m;function t(d,u){let f=`data-testim-${d}`,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 T={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(T))}catch(y){let T=y.message.toLowerCase().includes("quota"),w=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||T||w){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let E={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(E)),T||w)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(d){return d.function?d.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):d.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(d.otherParams)}function n(d,u){function f(){return d.apply(null,u)}return f.prototype=d.prototype,new f}let i={},o={},a={},c=s.functionParams,l=s.transactionId;try{let d=r(s);d.push(i,o,a);let u=((m=s.function)==null?void 0:m.params)||c,h=(e||n(Function,u)).apply(null,d);typeof Promise<"u"&&h instanceof Promise?(t(l,{type:"promise"}),h.then(g=>{t(l,{status:"done",success:!0,result:{resultValue:g,exports:i,exportsTest:o,exportsGlobal:a}})},g=>{t(l,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:i,exportsTest:o,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:h,exports:i,exportsTest:o,exportsGlobal:a}})}catch(d){t(l,{status:"failed",success:!1,result:{resultValue:d.toString(),exports:i,exportsTest:o,exportsGlobal:a}})}}});var da,Zn,cr,ma=S(()=>{"use strict";da=I(require("lodash"));B();me();W();de();Zn=P("base-js-step-action"),cr=class extends G{isExceedingMaxResultSize(t,r){var n;try{let i=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,o=O.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>o;return i?a:(a&&Zn.warn(`js result size exceeded ${o}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let n=`data-testim-${r}`;try{return window.sessionStorage.getItem(n)}catch(i){if(i.message.includes("sessionStorage")||i.message.includes("The operation is insecure")){let o=document.head.querySelector("#testim-storage-backup");return o?o.getAttribute(n):"{}"}throw i}},t)}constructJSFunParams(t){let r=t.incomingParams,n=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],i=[t.context,...r.as.functionArguments];return n.push(t.code),i.forEach(o=>{da.isObject(o)&&Mi(o,"seleniumElement",da.isEqual)}),{function:{params:n,args:i},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:n,step:{id:i=""}}=this,o=r.config.retryTimeout,a=r.data.timeToPlayStep-o,c=async()=>{let l;try{l=await this.executeGetStatus(t)}catch(u){Zn.warn("failed to get js status",{err:u}),l={value:'{ "status": "exception" }'}}let m;try{m=JSON.parse((l==null?void 0:l.value)||"{}")}catch{Zn.warn("non object value",{selRes:l}),m={status:"exception"}}let d=n.abortedSteps.find(u=>u.id===i);return d||(m?m.status==="done"?m:m.status==="failed"?{success:!1,shouldRetry:!0,result:m.result}:a-o<=0?Object.assign(m,{success:!1,shouldRetry:!0}):(a-=o,await pe(o),c()):{success:!0})};return c()}async executeInAut(t){let r=O.flags.experimentalPreCodeCompilation.isEnabled(),n=O.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(t),o=i.function.args.some(d=>Boolean(d==null?void 0:d.locatedElement)),a="undefined";if(r){let d=i.function.params.slice(0,-1);a=n?`async function(${d.join(",")}) {
253
253
  ${t.code}
254
254
  };`:`function(${d.join(",")}) {
255
255
  ${t.code}
@@ -259,18 +259,18 @@ Please make sure the CLI has stable access to the internet. ${Dc()?"(Internal: n
259
259
  var eventData = arguments[0];
260
260
  var funcToRun = ${a};
261
261
  return runCode.call(null, eventData, funcToRun);
262
- `;if(!r)return this.driver.executeJS(m,i);try{return await this.driver.executeJS(m,i)}catch(d){return this.handleExecutionError(d)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:c}=t;i.exports&&(n.data.exports=i.exports);let l={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...l,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...l,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...l,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...c&&{navigateToDifferentDomain:c}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(Qn.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),"stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:Qn.warn("stepResultId is not present in context",{step:t,context:r}),`${r.testResultId}:${n}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),i={transactionId:this.getTransactionId(t,r),id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(i);let o=await this.checkStatus(i.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var zt,hy=E(()=>{"use strict";ua();zt=class extends cr{isFailedResult(e){return e===!1}}});var ks,yy=E(()=>{"use strict";ua();ks=class extends cr{isFailedResult(e){return!e}}});var pa,by=E(()=>{"use strict";me();B();sa();pa=class extends H{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Ne(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(Kn[t]),this.setWithValueApi(e)}}});var da,Ty=E(()=>{"use strict";me();sa();da=class extends H{async performAction(){var i,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((i=this.step.keys)!=null&&i.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Kn[n])t.push(Kn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var wy={};z(wy,{selectOption:()=>PE});function PE(s,e){function t(r,n){let i=Element.prototype.matches,o=i&&isNativeFunction(i)?i:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(o=>{let a=document.createEvent("HTMLEvents");return a.initEvent(o,!0,!1),a}).forEach(o=>{if(e){n.dispatchEvent(o);return}r.dispatchEvent(o)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var vy=E(()=>{"use strict"});var ma,Sy=E(()=>{"use strict";me();B();de();ma=class extends H{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,i=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&i>=13&&!a)try{return await this.driver.elementIdClick(Ne(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(()=>(vy(),wy)),l=O.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),m=`
262
+ `;if(!r)return this.driver.executeJS(m,i);try{return await this.driver.executeJS(m,i)}catch(d){return this.handleExecutionError(d)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:c}=t;i.exports&&(n.data.exports=i.exports);let l={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...l,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...l,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...l,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...c&&{navigateToDifferentDomain:c}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(Zn.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),"stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:Zn.warn("stepResultId is not present in context",{step:t,context:r}),`${r.testResultId}:${n}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),i={transactionId:this.getTransactionId(t,r),id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(i);let o=await this.checkStatus(i.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var Kt,hy=S(()=>{"use strict";ma();Kt=class extends cr{isFailedResult(e){return e===!1}}});var ks,yy=S(()=>{"use strict";ma();ks=class extends cr{isFailedResult(e){return!e}}});var fa,by=S(()=>{"use strict";me();B();oa();fa=class extends G{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Ne(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(Jn[t]),this.setWithValueApi(e)}}});var ga,Ty=S(()=>{"use strict";me();oa();ga=class extends G{async performAction(){var i,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((i=this.step.keys)!=null&&i.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Jn[n])t.push(Jn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var wy={};z(wy,{selectOption:()=>kE});function kE(s,e){function t(r,n){let i=Element.prototype.matches,o=i&&isNativeFunction(i)?i:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(o=>{let a=document.createEvent("HTMLEvents");return a.initEvent(o,!0,!1),a}).forEach(o=>{if(e){n.dispatchEvent(o);return}r.dispatchEvent(o)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var vy=S(()=>{"use strict"});var ha,Sy=S(()=>{"use strict";me();B();de();ha=class extends G{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,i=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&i>=13&&!a)try{return await this.driver.elementIdClick(Ne(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(()=>(vy(),wy)),l=O.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),m=`
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(m,r,l)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var fa,Ey=E(()=>{"use strict";me();fa=class extends H{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var kE,ga,Iy=E(()=>{"use strict";me();kE=(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(){}}),ga=class extends H{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:n}=e,{width:i,height:o}=n,a=i/2,c=o/2,l=this.step.element.clickOffset;if(l&&this.step.shouldAccountForMouseOffsetInHover){let{x:d,y:u}=l;this.sessionPlayerInit.utils.isWithinTargetRect(kE(o,i,0,0),d,u)&&(a=d,c=u)}let m={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(c)}};return await this.driver.hover(t,m),{success:!0}}}});var Ry={};z(Ry,{wheel:()=>OE});var OE,xy=E(()=>{"use strict";OE=function(s,e){function r(a,c){function l(h,g,y){return y>h&&y<g}let m=a.pointerPosition||{},d=c.getBoundingClientRect(),u=m.originX&&l(d.left,d.left+d.width,m.originX)?m.originX:d.left+d.width/2,f=m.originY&&l(d.top,d.top+d.height,m.originY)?m.originY:d.top+d.height/2;return{x:u,y:f}}function n(a,c,l){let m=r(a,l),d=(c==null?void 0:c.modifiers)||{},u={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:m.x,clientY:m.y,bubbles:!0,cancelable:!0,ctrl:Boolean(d.ctrl),alt:Boolean(d.alt),shift:Boolean(d.shift),meta:Boolean(d.meta)};return new WheelEvent("wheel",u)}function i(a,c){if(a.length===0){e({state:"success"});return}if(!c)throw new Error("element not found");let l=a.shift(),m=n(l,s.eventData,c),d=a[0]?Math.min(a[0].timeStamp-l.timeStamp,200):200;c.dispatchEvent(m),setTimeout(()=>{i(a,c)},d)}let o=getLocatedElement(s.locatedElement);i(s.events,o)}});var ha,Ay=E(()=>{"use strict";me();ha=class extends H{async performAction(){var d;let{step:e,context:t}=this,{events:r,modifiers:n,button:i}=e;if(!(r!=null&&r.length))return;let o={events:r,eventData:{modifiers:n,button:i},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:c}=await Promise.resolve().then(()=>(xy(),Ry)),l=`
267
+ `;return(f=(await this.driver.executeJS(m,r,l)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var ya,Ey=S(()=>{"use strict";me();ya=class extends G{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var OE,ba,Iy=S(()=>{"use strict";me();OE=(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(){}}),ba=class extends G{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:n}=e,{width:i,height:o}=n,a=i/2,c=o/2,l=this.step.element.clickOffset;if(l&&this.step.shouldAccountForMouseOffsetInHover){let{x:d,y:u}=l;this.sessionPlayerInit.utils.isWithinTargetRect(OE(o,i,0,0),d,u)&&(a=d,c=u)}let m={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(c)}};return await this.driver.hover(t,m),{success:!0}}}});var Ry={};z(Ry,{wheel:()=>_E});var _E,xy=S(()=>{"use strict";_E=function(s,e){function r(a,c){function l(h,g,y){return y>h&&y<g}let m=a.pointerPosition||{},d=c.getBoundingClientRect(),u=m.originX&&l(d.left,d.left+d.width,m.originX)?m.originX:d.left+d.width/2,f=m.originY&&l(d.top,d.top+d.height,m.originY)?m.originY:d.top+d.height/2;return{x:u,y:f}}function n(a,c,l){let m=r(a,l),d=(c==null?void 0:c.modifiers)||{},u={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:m.x,clientY:m.y,bubbles:!0,cancelable:!0,ctrl:Boolean(d.ctrl),alt:Boolean(d.alt),shift:Boolean(d.shift),meta:Boolean(d.meta)};return new WheelEvent("wheel",u)}function i(a,c){if(a.length===0){e({state:"success"});return}if(!c)throw new Error("element not found");let l=a.shift(),m=n(l,s.eventData,c),d=a[0]?Math.min(a[0].timeStamp-l.timeStamp,200):200;c.dispatchEvent(m),setTimeout(()=>{i(a,c)},d)}let o=getLocatedElement(s.locatedElement);i(s.events,o)}});var Ta,Ay=S(()=>{"use strict";me();Ta=class extends G{async performAction(){var d;let{step:e,context:t}=this,{events:r,modifiers:n,button:i}=e;if(!(r!=null&&r.length))return;let o={events:r,eventData:{modifiers:n,button:i},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:c}=await Promise.resolve().then(()=>(xy(),Ry)),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:((d=(await this.driver.executeCodeAsync(l,a,o)).value)==null?void 0:d.state)==="success"}}}});var Cy={};z(Cy,{downloadFileAndFireDropEvent:()=>_E});var _E,Py=E(()=>{"use strict";_E=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 m=++o;return function(d){m in c||(c[m]=d,a++,e.length===a&&l.endWithCallback(c))}},endWith(m){l.endWithCallback=m}};return l}function n(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 i=r();e.forEach(o=>{n(o.url,o.name,i.waitOn())}),i.endWith(o=>{let a=createDropEvent(o);t.dispatchEvent(a)})}});var LE,ya,ky=E(()=>{"use strict";me();$();de();LE=P("drop-file-step-action"),ya=class extends H{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,i=this.getTarget(),o=O.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,o,LE),{downloadFileAndFireDropEvent:c}=await Promise.resolve().then(()=>(Py(),Cy)),l=`
273
+ `;return{success:((d=(await this.driver.executeCodeAsync(l,a,o)).value)==null?void 0:d.state)==="success"}}}});var Cy={};z(Cy,{downloadFileAndFireDropEvent:()=>LE});var LE,Py=S(()=>{"use strict";LE=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 m=++o;return function(d){m in c||(c[m]=d,a++,e.length===a&&l.endWithCallback(c))}},endWith(m){l.endWithCallback=m}};return l}function n(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 i=r();e.forEach(o=>{n(o.url,o.name,i.waitOn())}),i.endWith(o=>{let a=createDropEvent(o);t.dispatchEvent(a)})}});var DE,wa,ky=S(()=>{"use strict";me();W();de();DE=P("drop-file-step-action"),wa=class extends G{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,i=this.getTarget(),o=O.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,o,DE),{downloadFileAndFireDropEvent:c}=await Promise.resolve().then(()=>(Py(),Cy)),l=`
274
274
  const getLocatedElement = ${e.getLocatedElementCode};
275
275
  const createDropEvent = ${e.createDropEvent.toString()};
276
276
  const downloadFileAndFireDropEvent = ${c.toString()};
@@ -317,7 +317,7 @@ Please make sure the CLI has stable access to the internet. ${Dc()?"(Internal: n
317
317
  input.removeAttribute("disabled");
318
318
  input.focus();
319
319
  }
320
- }`}async function NE(s,e){let t=null;try{t=(await _c(s)).body}catch(n){if(DE.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let r=`${Oy.tmpdir()}/${e}`;return await _y.promises.writeFile(r,t),r}function ME(s){return se(s,e=>NE(e.url,e.name))}function FE(s,e){return e(s)}async function Dy(s,e){let t=await ME(s),r=await se(t,n=>FE(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var Oy,_y,DE,Ny=E(()=>{"use strict";Oy=I(require("os"));Ge();_y=require("fs");B();$();DE=P("input-file-utils")});function BE(){return`async function downloadAndUpload(locatedElement, fileUrls) {
320
+ }`}async function ME(s,e){let t=null;try{t=(await Nc(s)).body}catch(n){if(NE.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let r=`${Oy.tmpdir()}/${e}`;return await _y.promises.writeFile(r,t),r}function FE(s){return se(s,e=>ME(e.url,e.name))}function UE(s,e){return e(s)}async function Dy(s,e){let t=await FE(s),r=await se(t,n=>UE(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var Oy,_y,NE,Ny=S(()=>{"use strict";Oy=I(require("os"));Ge();_y=require("fs");B();W();NE=P("input-file-utils")});function jE(){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. ${Dc()?"(Internal: n
394
394
  element.dispatchEvent(new Event("change", { bubbles: true }));
395
395
  }
396
396
  element.removeEventListener("change", changeFiredHandler, true);
397
- }`}var ba,Ta,My=E(()=>{"use strict";Ny();me();$();B();de();ba=P("input-file-step-action"),Ta=class extends H{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){ba.info("workaround - stepaction - move element to visible position");let n=`
397
+ }`}var va,Sa,My=S(()=>{"use strict";Ny();me();W();B();de();va=P("input-file-step-action"),Sa=class extends G{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){va.info("workaround - stepaction - move element to visible position");let n=`
398
398
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
399
399
  var getVisibleElement = ${Ly(r)};
400
400
  return getVisibleElement.apply(null, arguments);
401
- `;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw ba.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let i="The element is not editable",o="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",c="element not interactable",l="element is not pointer- or keyboard interactable",m="invalid element state: Element is not currently interactable and may not be manipulated",d="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===m||f.startsWith(d)||f.startsWith(i)||f.startsWith(o)||f.startsWith(a)||f.includes(u)||f.includes(c)||f.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ba.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Ne(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=O.flags.overrideAzureStorageUrl.isEnabled(),n=O.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:c,driver:l}=this,m=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,c.testimServicesApi,r,ba);if(m.length===0)throw new Error("No files urls to upload");if(n&&(m=await Promise.all(m.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(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw va.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let i="The element is not editable",o="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",c="element not interactable",l="element is not pointer- or keyboard interactable",m="invalid element state: Element is not currently interactable and may not be manipulated",d="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===m||f.startsWith(d)||f.startsWith(i)||f.startsWith(o)||f.startsWith(a)||f.includes(u)||f.includes(c)||f.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw va.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Ne(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=O.flags.overrideAzureStorageUrl.isEnabled(),n=O.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:c,driver:l}=this,m=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,c.testimServicesApi,r,va);if(m.length===0)throw new Error("No files urls to upload");if(n&&(m=await Promise.all(m.map(async({name:u,url:f})=>{let h=await Wt(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 = ${BE()};
404
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,m);return}let d=await Dy(m,this.uploadFile);await this.uploadFilesAndForceVisibility(d,t)}}});var wa,va,Fy=E(()=>{"use strict";wa=require("url");me();va=class extends H{async updateBaseUrl(e){let t=new wa.URL(e),r=new wa.URL(this.context.recordedBaseUrl),n=new wa.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var Sa,Uy=E(()=>{"use strict";me();B();Sa=class extends H{async performAction(){await pe(this.step.durationMS||0)}}});var Ea,By=E(()=>{"use strict";me();Ea=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Zn,jy=E(()=>{"use strict";me();Zn=class extends H{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ia,$y=E(()=>{"use strict";me();Ia=class extends H{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Wy,Ju,Xu,Vy=E(()=>{"use strict";Wy=I(require("@applitools/spec-driver-webdriverio"));bi();we();Ju=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=vd["@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:Wy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Z(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Xu=new Ju});var Hy,Gy,ei,qy=E(()=>{"use strict";Hy=I(require("lodash"));me();$();Vy();Gy=P("pixel-validation-step-action"),ei=class extends H{async performAction(){var d,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,c=await Xu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},m;try{let f=await c.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};Hy.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),Gy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),m={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){Gy.error("Applitools SDK step failed",{err:f,info:f.info}),m={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Xu.handleApplitoolsSdkResult(this.context,m,this.step)}}});var Os,Yu=E(()=>{"use strict";Rs();Y();ua();Os=class extends cr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:m}=t,d={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await Is(i,o,a,d,c,l,m,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 lr,zy=E(()=>{"use strict";Yu();lr=class extends Os{isFailedResult(e){return e===!1}}});var Ra,Ky=E(()=>{"use strict";Yu();Ra=class extends Os{isFailedResult(e){return!e}}});var xa,Jy=E(()=>{"use strict";Rs();me();Y();xa=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await Es(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Ct?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ce?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Ur,Xy=E(()=>{"use strict";me();Ur=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,Yy=E(()=>{"use strict";me();be=class extends H{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Aa,Qy=E(()=>{"use strict";me();Aa=class extends H{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ca,Zy=E(()=>{"use strict";me();Ca=class extends H{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function jE(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Pa(s,e){jE($E,e),e.registerLocateStepActionUtils(Jn.getUtils(s))}var $E,Qu=E(()=>{"use strict";Jh();Qh();ay();cy();uy();my();hy();yy();by();Ty();Sy();Ey();Iy();Ay();ky();My();Fy();Uy();By();jy();$y();qy();zy();Ky();Jy();Xy();Yy();Qy();Zy();$E={locate:Jn,scroll:ia,mouse:oa,submit:fa,text:ca,"special-key":pa,"user-code":zt,"validation-code-step":zt,"wait-for-code-step":zt,"action-code-step":zt,"condition-step":ks,"skip-code-step":ks,"element-code-step":ks,"evaluate-expression":aa,"text-validation":Yn,"wait-for-text-validation":Yn,"select-option":ma,"drop-file":ya,"input-file":Ta,hover:ga,navigation:va,wheel:ha,sleep:Sa,refresh:Ea,"keyboard-shortcut-step":da,"api-validation":Zn,"api-action":Zn,"api-code-step":zt,"extract-text":Ia,"simple-ui-verification":ei,"wait-for-simple-ui-verification":ei,"cli-validation-download-file":Ur,"cli-wait-for-download-file":Ur,"network-validation-step":Ur,"cli-validation-code-step":lr,"cli-wait-for-code-step":lr,"cli-action-code-step":lr,"cli-api-code-step":lr,"cli-condition-step":Ra,"node-package":xa,"email-code-step":zt,"cli-email-code-step":lr,"sfdc-internal-test-step":Ca,"sfdc-recorded-step":Aa,"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":Ur,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var eb,WE,_s,Zu=E(()=>{"use strict";eb=["simple-ui-verification","wait-for-simple-ui-verification"],WE=[...eb,"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"],_s=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=WE.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return eb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var rb={};z(rb,{SeleniumTestPlayer:()=>ti});var tb,VE,ti,ep=E(()=>{"use strict";B();tb=require("@applitools/eyes-sdk-core");Bn();Y();$();Vu();Gh();zu();sa();zh();Ku();we();Qu();Zu();oe();VE=P("SeleniumTestPlayer"),ti=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new _s(na());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=Z();this.driver=n??new Or;let m=new ra(this.driver);this.stepActionFactory=new l(m),Pa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new ea(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let d=qh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ps(this.driver),FrameLocator:d,portSelector:ta,LocateElementPlayer:null,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:tb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ce&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){VE.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),i=[new URL(tt||gr).hostname].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(c=>a.url.includes(c))){this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var rp={};z(rp,{WorkerSelenium:()=>tp});function HE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>F(`Got event ${t}`))}var ka,GE,tp,sp=E(()=>{"use strict";B();$e();zn();$();Lt();Fo();ae();$u();Y();ep();we();ct();ka=P("worker-selenium"),GE=1e9,tp=class extends Nt{initPlayer(t){return new ti(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){F("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Cs(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await o.init({projectData:this.options.projectData,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:l,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.SELENIUM}),F("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),F("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,GE),await this.windowUtils.validatePageIsAvailable(),F("in WorkerSelenium after navigate")}catch(l){let m=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof At||m||d?new At(`Page '${c}' is not available`):(ka.error("failed to navigate to page",{baseUrl:c,err:l,whitelistedPublicIp:Zi(),initializedFromCache:eo()}),l)}}async runTestOnce(t,r){var d;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,c=n||"runner";Q.onWaitToTestComplete(this.id),HE(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),i.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await Wn(this.options))[this.testId]);let m=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,Ae.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ce&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(ka.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&&(ka.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(),F("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),F("right after super.runTestOnce in workerSelenium");let u=await m();return F("right after runSeleniumTest"),u}catch(u){throw ka.error("failed to run test once",{err:u}),u}}}});var sb,nb,He,qE,zE,np,Et,Oa=E(()=>{"use strict";sb=I(require("ora")),nb=require("jimp");oe();Ge();ge();$();ae();we();de();He=P("mobile-grid-service"),qE="https://tdc.tricentis-cloud.com",zE="https://ui.headspin.io",np=class{constructor(){this.gridsAppIdGetter={[_.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[_.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[_.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[_.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[_.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[_.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===_.TESTIM_HEADSPIN?`${r||bc}/${wc}/devices`:t===_.TESTIM_TDC?`${r||Tc}/${wc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:i})}catch(o){throw He.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw He.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Ys(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===_.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===_.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([_.BROWSERSTACK,_.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,c,l;if(t===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let m=await si({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=m==null?void 0:m[0])==null?void 0:a.name)||e.device}if(t===_.BROWSERSTACK)return((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName);if(t===_.SAUCELABS)return e.testobject_device_name;if(t===_.P_CLOUDY){if(e.pCloudy_DeviceFullName){let m=e.pCloudy_DeviceFullName.split("_");return`${m[0]} ${m[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:m}={},company:{companyId:d=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===_.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:v}=Z();y=v(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,m,d,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Cr(l,o,a,c,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),He.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===_.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),c=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:c}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),m=Buffer.from(c,"base64"),d=await nb.Jimp.fromBuffer(m),u=d.bitmap.width,f=d.bitmap.height;return{scaleFactor:u/l.width,width:u,height:f}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,c,l,m){let[d,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,m),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:c,gridId:l})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===_.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Vs}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===_.SAUCELABS?r.testobject_test_report_url:e.type===_.TESTIM_TVC?r.replayUrl:e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC?`${e.type===_.TESTIM_HEADSPIN?zE:qE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await Te(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:c}=t,l=await this.getTmaDeviceDetails(c,e);return await Cr(a,n,i,o,"RUNNING",{device:l}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:l}),l}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(O.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await op({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await ri({appId:e,projectId:t});return{appUrl:`${he()}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Nd*60))+1)*60*1e3,Math.max(Dd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[_.BROWSERSTACK]:{name:"Browserstack"},[_.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[_.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let c=r||t.mobileApp,l=(0,sb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let m=await ip({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});return l.succeed(`app uploaded successfully to ${a}`),m.gridAppId}catch(m){throw l.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:m,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:c="",project:l,authData:{token:m=""}={},gridData:d={}}=t,{gridId:u="",type:f=""}=d;if(!c&&e.isAppFromDevice)return n;if(c){He.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:m});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else He.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:d,testRunHandler:e}),y=f===_.BROWSERSTACK||f===_.TESTIM_TVC||f===_.P_CLOUDY;if(g){let T=t.projectData.type,v=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:d,projectType:T});v&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=g),!v&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!v&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var m,d;let{accessToken:n,user:i,host:o,key:a,type:c,apiUrl:l}=t;if(c===_.BROWSERSTACK){let u=`${Vs}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(c===_.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(c===_.TESTIM_HEADSPIN||c===_.TESTIM_TDC){let u=`${l}/${vc}/apps`;return l||(u=`${c===_.TESTIM_HEADSPIN?bc:Tc}/${vc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(c===_.TESTIM_TVC){let u=`${Md}/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&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(c===_.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await kc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(d=(m=JSON.parse(h).result)==null?void 0:m.files)==null?void 0:d.some(y=>y.file===e)}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},Et=new np});function ib({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"&&!KE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function JE({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==_.TESTIM_TDC&&e.type!==_.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function XE(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function YE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===_.TESTIM_TDC,a=s===_.TESTIM_HEADSPIN,c=o?"tdc":"headspin",l=a&&O.flags.enableBatchHeadSpin.isEnabled(),m=o&&(O.flags.enableBatchTDC.isEnabled()||O.flags.headSpinTdcEnableFlagCapability.isEnabled()),d=O.flags.increaseTDCRequestTimeout.isEnabled();return{[`${c}:capture.video`]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${c}:capture.network`]:!1},...i&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:XE(t),[`${c}:enableBatch`]:l||m,...!r&&{"appium:noReset":n},...d&&{[`${c}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function _a(s){return"id"in s?s.id:s.packageName}function QE(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function ZE({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":n},l=n==null?void 0:n.startsWith("http");n&&!l&&(c=QE(n,t.gridData.type));let d=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":d(),...r&&{"appium:bundleId":_a(r)},...n&&c};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":_a(r),"appium:appActivity":r.activity??".*"},...n&&c};default:throw Error(`unsupported mobile project ${s}`)}}function jr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:_a(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:_a(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function ob({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let c=YE(o.type,i,n);return ZE({projectType:s,sessionCaps:c,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Da({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 Na({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===_.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?Sc:i.deviceNameRegex:t==="ios"&&r===_.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":Sc:".*")}function eI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function tI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...La(s,Ls)}}function ab(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function rI(s){return ab(s,e=>e.startsWith("browserstack."),"browserstack.")}function sI(s){return ab(s,e=>!e.startsWith("browserstack."))}function cb(s){return!s||!lb(s)?"2.0.0":s}function lb(s){return s.split(".")[0]==="2"||s.includes("appium2")||["latest","stable"].includes(s)}function ub({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),c=e==="android"&&(n.test(s)||a),l=e==="ios"&&o.test(s),m=c||l;if(t){let d=lb(t);return!d&&m?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):d}return m}function La(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}async function nI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:c}){let{osVersion:l,deviceName:m}=n,d=(a==null?void 0:a.mobile)||{},{type:u}=i,f=eI(i,s),h=await si({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:w})=>{var S;return((S=d.staticAllocation)==null?void 0:S.deviceUdid)===w}),y=(g==null?void 0:g.osVersion)??Da({osVersion:l,mobileConfig:d}),T=(g==null?void 0:g.name)??Na({deviceName:m,mobileConfig:d,projectType:s,gridType:u}),v=ze(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),b={device:T,os_version:y,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":v,...c&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return jr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:c})}function iI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{user:d,key:u,type:f}=i,h=O.flags.enableAppium2pCloudy.isEnabled(),g=Da({osVersion:c,mobileConfig:m}),y=Na({deviceName:l,mobileConfig:m,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),v={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:d,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...v,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Fd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=tI(b)),t="",jr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Ls}})}function oI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{type:d}=i,u=Da({osVersion:c,mobileConfig:m}),f=Na({deviceName:l,mobileConfig:m,projectType:s,gridType:d}),h=(0,Br.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],ub({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},v={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:cb(g.appiumVersion??"stable"),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...La(h,Ls),"sauce:options":{...T,...v,...(0,Br.omit)(g,"appiumVersion")}};return jr({projectType:s,sessionCaps:b,appiumPrefix:Ls,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return jr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function aI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c}){let{osVersion:l,deviceName:m}=i,d=(c==null?void 0:c.mobile)||{},{type:u}=o,f=Da({osVersion:l,mobileConfig:d}),h=Na({deviceName:m,mobileConfig:d,projectType:e,gridType:u}),g=rI(i.browserstack),y=(0,Br.omit)(sI(i.browserstack),["automationName","platformName","project","build","name"]),T={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`},v=O.flags.enableAppium2BrowserStack.isEnabled();if(v||ub({osVersion:y.platformVersion||f,projectType:e,isBrowserStack:!0,appiumVersion:g.appiumVersion})){let w={...T,userName:o.user,accessKey:o.key,appiumVersion:v?"2.0.1":cb(g.appiumVersion),debug:!0,networkLogs:!0},S={"appium:platformVersion":f,"appium:deviceName":h,...La(y,Ls),"bstack:options":{...w,...(0,Br.omit)(g,"appiumVersion")}};return jr({projectType:e,sessionCaps:S,appiumPrefix:Ls,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}let b={...T,os_version:y.platformVersion||f,device:y.deviceName||h,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...y,...La(g,"browserstack.")};return jr({projectType:e,sessionCaps:b,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}async function cI(s){if(_.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type)return ob(s);if(_.TESTIM_TVC===s.gridInfo.type)return await nI(s);if(_.P_CLOUDY===s.gridInfo.type)return iI(s);if(_.SAUCELABS===s.gridInfo.type)return oI(s);if(_.BROWSERSTACK===s.gridInfo.type)return aI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function lI(s,e){var l,m;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,c={};return n==="dynamic"&&(!i&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!o&&((m=r==null?void 0:r.selector)!=null&&m.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),i&&(c.manufacturer=i),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function pb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);ib({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=Et.getGridConnection(e),c=await cI(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let y=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",T=lI(r,i==null?void 0:i.mobile);if(!(0,Br.isEmpty)(T)){let v=Object.entries(T).map(([b,w])=>w.split(",").map(S=>S===".*"||S==="="?"":`${b}:${S}`).join(",")).join(" ").trim();c[`${y}:selector`]=v}}let l=e.type===_.TESTIM_TVC?{alwaysMatch:c}:c,m=O.flags.increaseTDCRequestTimeout.isEnabled(),d=0,u=(0,ap.default)("2m"),f=(0,ap.default)("12m"),h=br(O.flags.appiumConnectionRetryCount.getValue(),d),g=br(O.flags.appiumConnectionRequestTimeout.getValue(),u);return m&&g<f&&(g=f),{...a,desiredCapabilities:c,connectionRetryTimeout:g,capabilities:l,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function db(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;ib({nativeAppMetadata:r,appPath:i,gridInfo:t}),JE({deviceUdid:l,gridInfo:t,testRunConfig:c});let m=l||((g=(h=c.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),d=await Et.getGridDirectConnection(t,m),f=ob({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return m&&(f["appium:udid"]=m),{...d,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function mb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=jr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function fb(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 ap,Br,Ls,KE,cp=E(()=>{"use strict";ap=I(require("ms"));de();ae();Oa();Br=require("lodash");B();oe();ge();Ls="appium:",KE=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.P_CLOUDY]});var Ma,hb=E(()=>{"use strict";Ma=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 Fa,yb=E(()=>{"use strict";B();Fa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=sn;this.getLinksFromUnescapeHTML=nn}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 lp,Ua,bb=E(()=>{"use strict";$();lp=P("mobile-frame-locator-mock"),Ua=class{foundFrameCallback(){return lp.info("foundFrameCallback-mock invoked"),{}}locate(){return lp.info("locate-mock invoked"),{}}async findFrame(){return lp.info("findFrame-mock invoked"),{}}}});var uI,wb,Tb,Ds,up=E(()=>{"use strict";uI=I(require("webdriverio")),wb=require("@applitools/eyes-sdk-core");hb();zu();$();yb();Ku();we();Qu();bb();Zu();Tb=P("appium-test-player"),Ds=class{constructor(e,t,r,n=uI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:m}=Z(),d=new Fa(this.driver);this.stepActionFactory=new l(d),Pa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new _s(na()),this.sessionPlayer=new a(e,{tabService:new Ma,cookieUtils:void 0,FrameLocator:Ua,portSelector:ta,LocateElementPlayer:m,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:wb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Tb.info("appium session deleted",{...i}))}catch(o){Tb.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Z();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function pI(s){return await Te(`${s}/api/status`)}async function vb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function Sb(s){if((await pI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Eb=E(()=>{"use strict";Ge()});var Ib={};z(Ib,{WorkerLocalTma:()=>fp});var $r,pp,dp,mp,fp,Rb=E(()=>{"use strict";Ge();cp();zn();B();$();Lt();up();we();Eb();Oa();$r=P("worker-appium"),pp=class extends Error{},dp=class extends Error{},mp=class extends Error{},fp=class extends Nt{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}=Z(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var S;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:c}=this.options;await Sb(o);let{project:l,authData:{token:m=""}={}}=this.options,{driver:d}=n,u=c.type,f=this.options.appId;if(f){let{mobileApp:A}=await Et.getMobileAppDataByAppId({appId:f,projectId:l,token:m});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:v,version:b},w]=await Promise.all([this.getAppStateFromDevice(o,a,T),vb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if($r.info("device status and app state",{deviceStatus:w,appInstalled:v,version:b,executionId:this.executionId,testResultId:this.testResultId}),!v&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!v&&y&&(await this.installApp(o,a,y),$r.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:`${(S=this.options.projectData)==null?void 0:S.name}-${this.options.project}`},D=mb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),V={capabilities:{udid:a,...D}};$r.info("requesting new appium session from TMA",{tmaSessionSettings:V,executionId:this.executionId,testResultId:this.testResultId});let x=await this.requestNewAppiumSessionFromTma(o,V,g);this.sessionData=x;let R=await d.attach({sessionId:x.sessionId,capabilities:D,options:{capabilities:D}});this.device=await Et.updateTmaDeviceDetails(a,this.options,t),$r.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:R.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:R.capabilities})}catch(A){throw $r.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new mp(c):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,c=(await Te(o)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await $t(n);await Xs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new dp(l,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new pp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Z(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device,nativeApp:t.nativeApp},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((d,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:d,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw $r.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw $r.error("failed to run test once",{err:l}),l}}}});var Ab={};z(Ab,{WorkerAppium:()=>gp});var xb,Wr,gp,Cb=E(()=>{"use strict";B();cp();xb=require("linkedom");zn();$();Lt();up();we();Oa();ae();fs();Wr=P("worker-appium"),gp=class extends Nt{initPlayer(t){return new Ds(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==_.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:c}=n,l=await Et.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),m=o==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let 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:d,appPath:l,androidActivityWait:m,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Et.lockDevice(i,this.options.deviceUdid),h=await db(f)):h=await pb({...f,shouldRunInEnhancedMode:a}),Wr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:d,capabilities:fb(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),Wr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Wr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await t.getOrientation()}catch(i){Wr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&Hf(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){Wr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===_.TESTIM_HEADSPIN||i===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===_.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,c=n||"runner",l=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let m;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:v,port:b,path:w}=await Et.getHeadSpinDeviceConnection(this.options.gridData,y);m=`${T}://${v}:${b}${w}`}else m=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device,nativeApp:t.nativeApp},a.playbackManager.appiumApi=new i(m,this.activeSession.sessionId,xb.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((v,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:v,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Wr.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,Ae.TEST_REACHED_CUSTOM_TIMEOUT_MSG)}catch(y){throw Wr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:test"}}});var Ba,Pb=E(()=>{"use strict";B();Bn();Y();Ba=class{constructor(e){this.id=e;this.driver=new Or}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 kb(){let s=await Promise.any(dI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var dI,ja,$a=E(()=>{"use strict";Ge();dI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];ja=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var Ob,Wa,_b=E(()=>{"use strict";Ob=I(require("ws"));B();$a();Wa=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=ja({timeout:e}),r=new Ob.default(this._cdpUrl,t),n=Qt(o=>{r.once("open",o)}),i=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([n,i]).then(()=>r),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((c,l)=>{this._cdpCallbacks.set(i,{resolve:c,reject:l})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var Ga,hp,Va,Lb=E(()=>{"use strict";B();Ga=I(require("chrome-launcher"));Lo();_b();Pn();hp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Wa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:m}=e,d=_o({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:m}),u=[...((h=d.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=d.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...Ga.Launcher.defaultFlags().filter(v=>v!=="--disable-extensions")];this.chrome=await Ga.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 wr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),gs(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},Va=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new hp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var yp={};z(yp,{WorkerExtension:()=>ni});function mI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Db(s){return mI(s)?s:new Error(s)}var Ze,ni,Ha=E(()=>{"use strict";$e();Y();zn();B();$();Lt();ae();Pb();Lb();ct();Ze=P("worker-ext"),ni=class extends Nt{initPlayer(){return this.options.useChromeLauncher?new Va(this.id):new Ba(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.EXTENSION})}catch(a){throw Ze.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Zi(),initializedFromCache:eo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;F("WorkerExtension runTestOnce");let o=async m=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(m.cdpTestRunner),d,Ae.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ce))throw u;return Ze.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(m,d,u)=>{try{let f=await m.url(d);return u.driverUrlFinished=!0,f}catch(f){throw Ze.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:d,urlLength:d.length}),f}},c=async m=>{let d=await e.onStarted(this.options.testStartTimeout);return m.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(F("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(y){throw Ze.warn("failed to run test via CDP",{err:y}),y}}let{driver:d}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let v=function(w){e.onCompletedCleanup(),Ze.warn("on browser closed error detected",{err:w,testResultId:r,executionId:n,testId:i}),d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b),w.type=Xr.BROWSER_CLOSED,T.abort(w)},b=function(w){d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b),Ze.warn("on keep alive failed error detected",{err:w,testResultId:r,executionId:n,testId:i}),w.type=Xr.KEEP_ALIVE_FAILED,T.abort(w)};var f=v,h=b;let y=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,y,u),c(u)]),this.options.testStartTimeout,Ae.TEST_START_TIMEOUT_MSG)}catch(w){if(!(w instanceof ce))throw w;Ze.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let T=new AbortController;d.registerToClosedBrowser(v),d.registerToKeepAliveFailed(b);try{let w=le(e.onCompleted(),this.testRunTimeout,Ae.TEST_COMPLETE_TIMEOUT_MSG),S=await xc(w,T.signal);d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b);try{await this.updateTestStatusOnGrid(d,Boolean(S.success),S.reason)}catch(V){Ze.error("Could not update the grid about the test status",{err:V})}d.isAlive()||(Ze.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let A=d.maxKeepAliveGap();return A>=3e4&&(Ze.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=A),{...S,...e.seleniumPerfStats.getStats()}}catch(w){throw Ze.warn("timeout wait until test completed",{err:w,testResultId:r,executionId:n,testId:i}),Db(w)}finally{d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b)}}catch(y){throw Ze.warn("failed to start url",{err:y}),Db(y)}};t.driver.start();try{return await super.runTestOnce(e,t),F("WorkerExtension super.runTestOnce"),await l()}catch(m){throw Ze.error("failed to run test",{err:m,testId:e.testId,resultId:e.testResultId}),m}}}});var Tp={};z(Tp,{WorkerExtensionSingleBrowser:()=>bp});var fI,gI,bp,wp=E(()=>{"use strict";$e();B();$();Bu();Lt();Ha();fI=P("base-worker"),gI=500,bp=class extends ni{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await qn(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,i){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(fI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let i=this.handleQuarantine(t);if(i)return i;F("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await pe(gI)}}});var vp,qa,Nb=E(()=>{"use strict";Bn();oe();$e();Cl();ct();wu();Y();$();ae();Rh();Go();vp=P("worker-manager"),qa=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case K.SELENIUM:return(await Promise.resolve().then(()=>(sp(),rp))).WorkerSelenium;case K.APPIUM:return t?(await Promise.resolve().then(()=>(Rb(),Ib))).WorkerLocalTma:(await Promise.resolve().then(()=>(Cb(),Ab))).WorkerAppium;default:return jn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(wp(),Tp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Ha(),yp))).WorkerExtension}else switch(r){case(Nr.find(n=>n===r)&&jn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(wp(),Tp))).WorkerExtensionSingleBrowser;case Nr.find(n=>n===r):return(await Promise.resolve().then(()=>(Ha(),yp))).WorkerExtension;case Hn.find(n=>n===r):return(await Promise.resolve().then(()=>(sp(),rp))).WorkerSelenium;default:throw new C(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return F("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{F("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,c){if(e&&e.length===0)return;let l=!1,m=0,d=(u,f)=>new Promise(h=>{var ie,Ie,It,Gr,k,N,j,J;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Vo(r,n,e,i,o,t),this.combinedTestResults={};let T=((ie=i.company)==null?void 0:ie.ucid)||"",v=(Ie=i.company)==null?void 0:Ie.companyId,b=(It=i.company)==null?void 0:It.name,w=i.source||"cli",S=i.user,A=(Gr=i.company)==null?void 0:Gr.planType,D=(k=i.company)==null?void 0:k.isStartUp,V=(N=i.projectData)==null?void 0:N.name,x=(j=i.projectData)==null?void 0:j.type,R=i.lightweightMode,L=(J=i.gridData)==null?void 0:J.type,M=(_e,Rt,ve,uc,li,pc)=>(m++,Cf({executionId:r,projectId:g,testId:Rt,resultId:ve,ucid:T,companyId:v,companyName:b,projectName:V,companyPlan:A,source:w,user:S,lightweightMode:R,isStartUp:D,projectType:x,appSource:pc,gridType:L}),t.testStartAndReport(_e,r,ve,uc,li)),G=async(_e,Rt,ve,uc,li,pc)=>{var gd,hd,yd;m--;let et={...(R==null?void 0:R.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...i.host&&{gridHost:i.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((gd=i.gridData)==null?void 0:gd.name),et.gridType=(hd=i.gridData)==null?void 0:hd.type,et.gridProvider=(yd=i.gridData)==null?void 0:yd.provider):i.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):i.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):i.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):i.browserstack?et.gridName="browserstack-from-options":i.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(_e,ve,r,uc,li,et).catch(JT=>vp.error("testEndAndReport threw an error",{err:JT})),li)return;this.combinedTestResults[ve.resultId]=ve,Pf({executionId:r,projectId:g,testId:Rt,resultId:ve.resultId,result:ve,ucid:T,companyId:v,companyName:b,projectName:V,companyPlan:A,source:w,user:S,lightweightMode:R,logger:vp,isStartUp:D,projectType:x,appSource:pc}),c&&!ve.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===y||l&&m===0)&&h(this.combinedTestResults)},W=(_e,Rt)=>{this.combinedTestResults[Rt.resultId]=Rt,t.onTestIgnored(_e,Rt.resultId),m--,(Object.keys(this.combinedTestResults).length===y||l&&m===0)&&h(this.combinedTestResults)},q=(_e,Rt)=>t.onGridSlot(_e,Rt);for(i.userData={loginData:{...Ir(),refreshToken:Yi(),authData:Ir(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he()},F("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,M,G,q,W)});try{let u=await Ot(),f=await Qi(),h=await d(u,f);if(this.workers.size>0&&this.workers.clear(),l)throw new Xt;return h}catch(u){throw vp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var ii,Mb,za,Sp,Ep,Vr,Ip=E(()=>{"use strict";ii=I(require("lodash"));B();$();oe();ae();$e();cs();Al();Cl();ge();Mb=require("uuid");_f();B();Lt();hg();Y();Nb();de();Go();({CLI_MODE:za}=Wt),Sp=P("test-plan-runner"),Ep=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return Ep._id}async runTestAllPhases(e,t,r,n,i,o,a,c){let l={},m=new qa(this.customExtensionLocalLocation),d=async()=>{let g=i.beforeParallel||1,y=!0,T=await m.runTests(e,c,o,a,i,n,g,y);Object.assign(l,T)},u=async()=>{let g=vi||i.parallel,y=!1;F("right before this.workerManager.runTests");let T=await m.runTests(t,c,o,a,i,n,g,y);F("right after this.workerManager.runTests"),Object.assign(l,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await m.runTests(r,c,o,a,i,n,g,y);Object.assign(l,T)};kf({executionId:o,projectId:i.project}),F("right before runBeforeTests");try{return await d(),F("right before runTestPlanTests"),await u(),F("right after runTestPlanTests"),await f(),l}catch(g){if(Sp.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,T,v,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===za.SELENIUM){let[{getSessionPlayer:w},{makeSDK:S}]=await Promise.all([Promise.resolve().then(()=>(we(),ir)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=w();await A.closeBatch(o,S);return}let g;try{if(!((b=(v=(T=i.company)==null?void 0:T.activePlan)==null?void 0:v.premiumFeatures)!=null&&b.applitools)||(g=await Cp(i.project),ii.default.isEmpty(g)||!o))return;let{runKey:w,url:S}=g,A=require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}),D=1e4;await le(A.closeBatches({settings:{batchIds:[o],serverUrl:S,apiKey:w}}),D)}catch{}}}async runTestPlan(e,t,r,n,i,o,a,c){var b,w,S;let l=re(),m=n.project;Jd(l),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let d=[...e,...t,...r],u=new Eo(d,n,o,a),f=ii.default.chain(d).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:d.map(A=>A.name),y=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,m,this.startTime,i,g);F("before testListInfoPromise");let T=await y;(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,l,c,h),F("before runTestAllPhases");let v=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,l,i||"All Tests",u);return F("before executionEnd"),await u.executionEnd(l),F("after executionEnd"),{results:v,executionId:l,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(ue.colorString(ue.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await Rp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await xp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){Sp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(m){return ii.default.flattenDeep(Object.values(m)).reduce((d,u)=>d.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async m=>{let d=await oi(o,e.testPlan,[m],t,e.intersections);d.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=d.testPlansData[f]})}),await se(e.testPlan,async m=>{let d=await oi(o,[m],e.testPlanIds,t,e.intersections);d.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=d.testPlansData[f]})})):a=await oi(o,e.testPlan,e.testPlanIds,t,e.intersections);let c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==za.APPIUM&&await Fu(e,r(l)),await se(c,async m=>{var h;let d=m.testPlanId;n[d]={};let u={...e};u.baseUrl||=m.startUrl,u.appId||=((h=m.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=m.gridId,e.grid&&delete u.gridId,u.gridData=await hf(e,m);let f=u.overrideExecutionName||m.name;return await se(l[d],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,d,t);Q.onTestPlanFinished(y.results,m.name,this.startTime,y.executionId,!1),n[d][y.executionId]=y.results;let T=Object.keys(n[d]).map(S=>({executionId:S,status:Mu(n[d][S])})),v=Object.keys(n[d]).map(S=>n[d][S]).reduce((S,A)=>Object.assign(S,A),{}),b=Mu(v);Object.assign(i,v);let w=b?T[0].executionId:T.find(S=>!S.status).executionId;return await Ap(o,d,{success:b,executions:T,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var c;Sp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),F("before getSuite");let r=await Ah(e,t);if(F("after getSuite"),!((c=r==null?void 0:r.tests[0])!=null&&c.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;F("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===za.APPIUM&&(a=await ri({appId:e.appId,projectId:e.project})),await se(r.tests,async l=>{if(a&&l.forEach(d=>{"nativeApp"in d&&(d.nativeApp=a)}),e.resultId){let d=l[0];d.resultId=e.resultId,l=[d]}e.mode!==za.APPIUM&&await Fu(e,l),F("right before runTestPlan");let m=await this.runTestPlan([],l,[],e,i,null,t,o);return F("right after runTestPlan"),await Q.onTestPlanFinished(m.results,i,this.startTime,m.executionId,o),m})}async run(e){let t=vn(),r=[];await this.reportTestRunnerStarted(e.project,e),en(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ii.default.flattenDeep(r);return F("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),F("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Vr=Ep;Vr._id=(0,Mb.v4)()});var Ce={};z(Ce,{addTestRetry:()=>au,clearTestResult:()=>Du,deleteCloudflareTunnel:()=>Mp,fetchLambdatestConfig:()=>uu,fixGridAppIDStructure:()=>op,forceUpdateCloudflareTunnelRoutes:()=>Np,getAllGrids:()=>xl,getAppDetails:()=>ri,getApplitoolsIntegrationData:()=>Cp,getBrowserStackSessionMetaData:()=>RI,getCloudflareTunnel:()=>Dp,getEditorUrl:()=>SI,getGridSlot:()=>Rl,getHybridGridProvider:()=>Il,getLabFeaturesByProjectId:()=>vu,getMobileDevicesFromGrid:()=>si,getRealData:()=>eu,getS3Artifact:()=>_n,getS3ArtifactText:()=>Zl,getSuiteTestList:()=>Uu,getTestPlan:()=>vI,getTestPlanTestList:()=>oi,getTestResults:()=>Dr,getUsageForCurrentBillingPeriod:()=>_p,initializeUserWithAuth:()=>Lp,isTestResultCompleted:()=>Lu,keepAliveCompanySlots:()=>Yl,keepAliveGrid:()=>Sl,loadSfdcCredential:()=>Op,loadTest:()=>Vn,releaseCompanySlot:()=>Jl,releaseGridSlot:()=>El,reportExecutionFinished:()=>Io,reportExecutionStarted:()=>ou,reportRunnerFinished:()=>xp,reportRunnerStarted:()=>Rp,requestCompanySlot:()=>Kl,saveRemoteStep:()=>Eu,saveTestPlanResult:()=>Ap,updateCompanySlot:()=>Xl,updateExecutionTests:()=>iu,updateRemoteRunFailure:()=>Fp,updateTestDataArtifact:()=>Ro,updateTestResult:()=>Jo,updateTestStatus:()=>Cr,uploadAppToGrid:()=>ip,uploadRunDataArtifact:()=>Nu,validateUserAccessKey:()=>wl});async function Ns(){let s=await Ot();if(!s)throw new Error("Failed to get token from server");return{[Vc]:Vr.id,Authorization:`Bearer ${s}`}}async function Re({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await Ns(),o={...t,...i};return Ve({url:`${he()}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function TI(s,e,t,r={},n=void 0){let i=await Ns(),o={...r,...i};return await Xs(`${he()}${s||""}`,e,t,o,n)}async function ai(s,e){let t=await Ns();return await Oc(`${he()}${s||""}`,e,t)}async function Ub(s,e){let t=await Ns();return await Js(`${he()}${s||""}`,e,t)}async function wI(s,e){let t=await Ns();return await Ys(`${he()}${s||""}`,e||void 0,t)}async function ke(s,e,t,r){let n=await Ns();return await Te(`${he()}${s||""}`,e||void 0,n,r,t)}function _n(s,e){return(0,ee.default)(()=>ke(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function Zl(s){return(0,ee.default)(()=>wI(`/storage${s}`))}async function Rp(s,e){return await Re({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function xp(s){return await Ub("/test-runner",{projectId:s})}async function vI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>ke("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function Op({branch:s,projectId:e}){let t=await(0,ee.default)(()=>ke(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function Vn({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>ke(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function Ap(s,e,t){return(0,ee.default)(()=>Re({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Cr(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>ai("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:hI,...i}),{retries:o,factor:1})}function iu(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>ai("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:te,factor:1})}async function ou({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:m}){let{isCi:d}=await Promise.resolve().then(()=>(no(),Rf));return Re({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:m,metadata:{isCiRun:d,localRunUserId:c,isLocalRun:l}},retry:3})}function Io(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>ai("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function oi(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Uu({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:m}){return(0,ee.default)(()=>Re({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:m}}),{retries:te,factor:1})}async function ri({appId:s,projectId:e}){try{return await(0,ee.default)(()=>ke(`/mobile-app/app/${s}?projectId=${e}`),{retries:te,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function _p(s){try{return await(0,ee.default)(()=>ke(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){Mt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Lu(s,e,t){return(0,ee.default)(()=>ke(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function Dr(s,e,t,r){return(0,ee.default)(()=>ke(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function Sl(s,e){return Re({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function El(s,e,t,r,n){return Re({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Il(s){return Re({url:"/grid/hybrid/provider",body:s})}function Rl(s){return(0,ee.default)(()=>ke("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Lp({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:m}){var d,u;try{return await(0,ee.default)(()=>Ve({url:`${he()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:m},timeout:6e4}),{retries:te,factor:1})}catch(f){if(Mt.error("error initializing info from server",f),(d=f.message)!=null&&d.includes("Bad Request"))throw new C("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 C("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(Pp.default[y](Pp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Mt.error("Error parsing error message from server",f)}throw f}}async function SI(){if(tt)return{editorUrl:tt};try{return await(0,ee.default)(()=>ke("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return Mt.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function xl(s){return(0,ee.default)(()=>ke("/grid",{companyId:s}),{retries:te,factor:1})}function eu(s,e,t){return(0,ee.default)(()=>ke(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function Jo(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function Du(s,e,t,r){return(0,ee.default)(()=>Re({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function Eu(s,e,t,r){return(0,ee.default)(()=>Re({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function EI(s){return s.startsWith("/")?s:`/${s}`}function II(s,e,t){let r=EI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Bb(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,c=`${e}/${t}/${a}`,l=II(c,bI,s),m=Buffer.from(Fb.gzip(r,{level:3})),d={file:{fileName:a,buffer:m}};return await(0,ee.default)(()=>TI(`/storage${l}`,{},d,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),l}function au({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Re({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function Cp(s){try{return await ke(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Mt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Dp(s,e){try{return await ai("/tunnel",{companyId:s,routes:e})}catch(t){return Mt.warn("could'nt get tunnel.",{err:t}),{}}}async function Np(s,e){try{return await Re({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Mt.warn("could'nt get tunnel.",{err:t});return}}async function Mp(s,e){try{return await Ub(`/tunnel/${e}`,{companyId:s})}catch(t){Mt.warn("could'nt get tunnel.",{err:t});return}}function Fp(s){return Ve({url:`${he()}/result/remoteRunFailure`,body:s})}async function si({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${yI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>ke(i,{projectId:s}),{retries:te,factor:1})}catch(o){return Mt.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function ip({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Re({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function op(s){return(0,ee.default)(()=>Re({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Kl(s,e){return(0,ee.default)(()=>Re({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Jl(s,e,t){return(0,ee.default)(()=>Re({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Xl(s,e,t){return(0,ee.default)(()=>ai("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Yl(s,e,t){return Re({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function RI(s,e){return await Te(`${Vs}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function wl(s){try{return await ke("/v2/project/validateUserAccessKey",s),!0}catch(e){return Mt.error("error validating user access key",{error:e}),!1}}var Pp,ur,Fb,ee,kp,hI,Mt,te,yI,bI,uu,vu,Nu,Ro,ge=E(()=>{"use strict";Pp=I(require("chalk")),ur=I(require("lodash")),Fb=I(require("pako"));B();oe();ae();Ge();ct();ee=I(require("p-retry")),kp=I(require("object-hash"));Y();$();Ip();hI=rt(),Mt=P("testim service api"),te=3,yI="/grid",bI="test-result-artifacts";uu=async(s,e)=>(0,ee.default)(()=>ke("/grid/lt/config",{companyId:s,...e&&{projectId:e}}),{retries:te,factor:1}),vu=async s=>(0,ee.default)(()=>ke(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Nu=ur.memoize(async(s,e,t,r)=>{if(!ur.isEmpty(r))return await Bb(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,kp.default)(r)}:${e}:${t}`),Ro=ur.memoize(async(s,e,t,r,n)=>!r||ur.isEmpty(r)?void 0:await Bb(s,e,t,JSON.stringify((()=>{let o=ur.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:jc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,kp.default)(r)}:${e}:${t}`)});function Ka(){return rt()}var Up=E(()=>{"use strict";B()});function CI(s){K.EXTENSION!==s&&process.nextTick(()=>{try{(we(),qe(ir)).getSessionPlayer()}catch{}})}function PI(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let n=r.color||"yellow",i=r.bgColor||"bgBlack";console.log(Bp.default[i](Bp.default[n](r.text)))})}function kI(s,e){let{serviceUrl:t}=s;Gs(t),kt(async()=>s,Yr.CACHE_FN_NAME,Yr.TTL,{serviceUrl:t})(),Ut.setRegion(Tg[bs(e)])}async function ci(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,m=Boolean(n==null?void 0:n.general),d=Boolean(i||o),u=m?AI:xI,f=Ka(),h=Fc(),g=await Vm(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!d)try{y=await kb()}catch(b){jb.error("failed to get public ip",b)}let T=!0;F("before initializeUserWithAuth");let v=await kt(async()=>(CI(a),T=!1,await Lp({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:d,publicIp:y,gridId:c,grid:l,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:m,localGrid:d,gridId:c,grid:l,publicIp:y})();return PI(v),kI(v.clientConfig,e),s.publicIps=[v.clientPublicIp],F("after initializeUserWithAuth"),y&&v.clientPublicIp&&v.clientPublicIp!==y&&(jb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:v.clientPublicIp}),s.publicIps.push(y)),uf(v.authData,{projectId:e,token:t,userAccessKey:r,publicIp:v.clientPublicIp,initializedFromCache:T}),v}var Bp,jb,xI,AI,$b=E(()=>{"use strict";Bp=I(require("chalk"));$e();ge();er();ct();$a();ae();$();de();Up();B();os();oe();Ao();jb=P("initializeUserWithAuth"),xI=1e3*60*5,AI=1e3*60*60*10});async function Gb(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Xi():s.chromeBinaryLocation,e=ln({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 Sr(s.playerLocation,s.canary),s.mode!==K.SELENIUM&&s.mode!==K.APPIUM&&!s.ext&&await ul(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await ll(s.installCustomExtension,n)}return await e,t}async function Hb(s){var o;OI.info("prepare MockNetwork",{location:s});let e=await Nc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Wb*1e6)throw new Error(`${jp} exceeded ${Wb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${jp} cannot be parsed.${Ja.EOL}${a}`)}let n=new Vb.default;if(!n.validate(Yc,r)){let a=(o=n.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Ja.EOL);throw new Error(`${jp} is malformed.${Ja.EOL}${a}`)}return r.entries}var Ja,Vb,Wb,jp,OI,$p=E(()=>{"use strict";Ja=I(require("node:os"));B();Sm();pn();Vb=I(require("ajv"));ae();fl();$();$b();Wb=1,jp="JSON file supplied to --mock-network-pattern",OI=P("prepare runner")});function Xb(s){return s.start&&ls(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Yb(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=xo(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 Qb=E(()=>{"use strict";Dn();us();Y()});var Ms,Hp,Zb=E(()=>{"use strict";Ms="SECRETS",Hp={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(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${r}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(n);if(l){let m=l[1];o[c]=e[m]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(n);if(l){let m=l[1];o[a]=e[m]??c}}else typeof c=="object"&&c!==null&&i(c)})};i(s)}}});var Xp={};z(Xp,{doLogin:()=>Jp,getProjectId:()=>FI,getToken:()=>UI});async function FI(){return rT("projectId")}async function UI(){return rT("token")}function tT(s,e){return Promise.race([s,pe(e).then(()=>{throw new ce("timeout")})])}async function BI(){let s=(await import("express")).default(),e=async function(){return tT(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),Ce)),{editorUrl:n}=await r();ho(`${n}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${tt||gr}`)}return await e}async function Jp({overwriteExisting:s=!0,projects:e=null}={}){let t=qp.homedir(),r=zp.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await tT(BI(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,c.succeed(),await eT(r,i);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(m=>({title:m.name,value:m}))});i.token=l.project.ci.token,i.projectId=l.project.id,await eT(r,i);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function eT(s,e){await Kp.promises.writeFile(s,Ya.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function rT(s){let e=qp.homedir(),t=zp.join(e,".testim"),r=await ye(t),n={};if(r)try{n=Ya.parse((await Kp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var qp,zp,Ya,Kp,Qa=E(()=>{"use strict";qp=I(require("os")),zp=I(require("path")),Ya=I(require("yaml"));B();Kp=require("fs");Y();Gl();oe()});var pT={};z(pT,{process:()=>KI,program:()=>p});var Qp,aT,Za,cT,Kt,Fe,lT,jI,Me,ed,$I,WI,nT,uT,VI,Zp,ec,td,Yp,Ft,iT,GI,HI,p,qI,zI,oT,KI,rd=E(()=>{"use strict";Qp=I(require("ms")),aT=I(require("chalk")),Za=I(require("node:fs")),cT=I(require("node:url")),Kt=I(require("lodash")),Fe=I(require("node:path"));B();Dn();Qb();er();lT=require("commander");ae();Y();Hr();B();de();Zb();Go();Ao();oe();jI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Me=(s,e)=>(e.push(s),e),ed=new lT.Command,$I=s=>s.split(","),WI=(s,e)=>!s||s.length===0?e:s,nT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],uT=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function m(g){return g.includes("--high-speed")}function d(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")}ed.help(g=>g.split(`
403
+ const downloadAndUploadFile = ${jE()};
404
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,m);return}let d=await Dy(m,this.uploadFile);await this.uploadFilesAndForceVisibility(d,t)}}});var Ea,Ia,Fy=S(()=>{"use strict";Ea=require("url");me();Ia=class extends G{async updateBaseUrl(e){let t=new Ea.URL(e),r=new Ea.URL(this.context.recordedBaseUrl),n=new Ea.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var Ra,Uy=S(()=>{"use strict";me();B();Ra=class extends G{async performAction(){await pe(this.step.durationMS||0)}}});var xa,By=S(()=>{"use strict";me();xa=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var ei,jy=S(()=>{"use strict";me();ei=class extends G{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Aa,$y=S(()=>{"use strict";me();Aa=class extends G{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Wy,Qu,Zu,Vy=S(()=>{"use strict";Wy=I(require("@applitools/spec-driver-webdriverio"));Ti();we();Qu=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=Ed["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:Wy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Z(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Zu=new Qu});var Hy,Gy,ti,qy=S(()=>{"use strict";Hy=I(require("lodash"));me();W();Vy();Gy=P("pixel-validation-step-action"),ti=class extends G{async performAction(){var d,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,c=await Zu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},m;try{let f=await c.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};Hy.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),Gy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),m={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){Gy.error("Applitools SDK step failed",{err:f,info:f.info}),m={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Zu.handleApplitoolsSdkResult(this.context,m,this.step)}}});var Os,ep=S(()=>{"use strict";Rs();Y();ma();Os=class extends cr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:m}=t,d={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await Is(i,o,a,d,c,l,m,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 lr,zy=S(()=>{"use strict";ep();lr=class extends Os{isFailedResult(e){return e===!1}}});var Ca,Ky=S(()=>{"use strict";ep();Ca=class extends Os{isFailedResult(e){return!e}}});var Pa,Jy=S(()=>{"use strict";Rs();me();Y();Pa=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await Es(e,r,n,t,i,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,Xy=S(()=>{"use strict";me();Br=class extends G{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,Yy=S(()=>{"use strict";me();be=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ka,Qy=S(()=>{"use strict";me();ka=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Oa,Zy=S(()=>{"use strict";me();Oa=class extends G{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function $E(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function _a(s,e){$E(WE,e),e.registerLocateStepActionUtils(Xn.getUtils(s))}var WE,tp=S(()=>{"use strict";Jh();Qh();ay();cy();uy();my();hy();yy();by();Ty();Sy();Ey();Iy();Ay();ky();My();Fy();Uy();By();jy();$y();qy();zy();Ky();Jy();Xy();Yy();Qy();Zy();WE={locate:Xn,scroll:ca,mouse:la,submit:ya,text:pa,"special-key":fa,"user-code":Kt,"validation-code-step":Kt,"wait-for-code-step":Kt,"action-code-step":Kt,"condition-step":ks,"skip-code-step":ks,"element-code-step":ks,"evaluate-expression":ua,"text-validation":Qn,"wait-for-text-validation":Qn,"select-option":ha,"drop-file":wa,"input-file":Sa,hover:ba,navigation:Ia,wheel:Ta,sleep:Ra,refresh:xa,"keyboard-shortcut-step":ga,"api-validation":ei,"api-action":ei,"api-code-step":Kt,"extract-text":Aa,"simple-ui-verification":ti,"wait-for-simple-ui-verification":ti,"cli-validation-download-file":Br,"cli-wait-for-download-file":Br,"network-validation-step":Br,"cli-validation-code-step":lr,"cli-wait-for-code-step":lr,"cli-action-code-step":lr,"cli-api-code-step":lr,"cli-condition-step":Ca,"node-package":Pa,"email-code-step":Kt,"cli-email-code-step":lr,"sfdc-internal-test-step":Oa,"sfdc-recorded-step":ka,"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 eb,VE,_s,rp=S(()=>{"use strict";eb=["simple-ui-verification","wait-for-simple-ui-verification"],VE=[...eb,"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"],_s=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=VE.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return eb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var rb={};z(rb,{SeleniumTestPlayer:()=>ri});var tb,GE,ri,sp=S(()=>{"use strict";B();tb=require("@applitools/eyes-sdk-core");jn();Y();W();qu();Gh();Xu();oa();zh();Yu();we();tp();rp();oe();GE=P("SeleniumTestPlayer"),ri=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new _s(aa());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=Z();this.driver=n??new _r;let m=new ia(this.driver);this.stepActionFactory=new l(m),_a(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new sa(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let d=qh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ps(this.driver),FrameLocator:d,portSelector:na,LocateElementPlayer:null,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:tb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ce&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){GE.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),i=[new URL(tt||hr).hostname].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(c=>a.url.includes(c))){this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var ip={};z(ip,{WorkerSelenium:()=>np});function qE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>F(`Got event ${t}`))}var La,HE,np,op=S(()=>{"use strict";B();$e();Kn();W();Dt();Bo();ae();Gu();Y();sp();we();ct();La=P("worker-selenium"),HE=1e9,np=class extends Mt{initPlayer(t){return new ri(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){F("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Cs(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await o.init({projectData:this.options.projectData,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:l,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.SELENIUM}),F("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),F("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,HE),await this.windowUtils.validatePageIsAvailable(),F("in WorkerSelenium after navigate")}catch(l){let m=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof Ct||m||d?new Ct(`Page '${c}' is not available`):(La.error("failed to navigate to page",{baseUrl:c,err:l,whitelistedPublicIp:to(),initializedFromCache:ro()}),l)}}async runTestOnce(t,r){var d;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,c=n||"runner";Q.onWaitToTestComplete(this.id),qE(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),i.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await Vn(this.options))[this.testId]);let m=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,Ae.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ce&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(La.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&&(La.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(),F("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),F("right after super.runTestOnce in workerSelenium");let u=await m();return F("right after runSeleniumTest"),u}catch(u){throw La.error("failed to run test once",{err:u}),u}}}});var sb,nb,He,zE,KE,ap,It,Da=S(()=>{"use strict";sb=I(require("ora")),nb=require("jimp");oe();Ge();ge();W();ae();we();de();He=P("mobile-grid-service"),zE="https://tdc.tricentis-cloud.com",KE="https://ui.headspin.io",ap=class{constructor(){this.gridsAppIdGetter={[_.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[_.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[_.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[_.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[_.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[_.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===_.TESTIM_HEADSPIN?`${r||vc}/${Ec}/devices`:t===_.TESTIM_TDC?`${r||Sc}/${Ec}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:i})}catch(o){throw He.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw He.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Ys(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===_.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===_.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([_.BROWSERSTACK,_.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,c,l;if(t===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let m=await ni({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=m==null?void 0:m[0])==null?void 0:a.name)||e.device}if(t===_.BROWSERSTACK)return((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName);if(t===_.SAUCELABS)return e.testobject_device_name;if(t===_.P_CLOUDY){if(e.pCloudy_DeviceFullName){let m=e.pCloudy_DeviceFullName.split("_");return`${m[0]} ${m[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:m}={},company:{companyId:d=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===_.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=Z();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,m,d,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Pr(l,o,a,c,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),He.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===_.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),c=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:c}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),m=Buffer.from(c,"base64"),d=await nb.Jimp.fromBuffer(m),u=d.bitmap.width,f=d.bitmap.height;return{scaleFactor:u/l.width,width:u,height:f}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,c,l,m){let[d,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,m),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:c,gridId:l})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===_.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Vs}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===_.SAUCELABS?r.testobject_test_report_url:e.type===_.TESTIM_TVC?r.replayUrl:e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC?`${e.type===_.TESTIM_HEADSPIN?KE:zE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await Te(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:c}=t,l=await this.getTmaDeviceDetails(c,e);return await Pr(a,n,i,o,"RUNNING",{device:l}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:l}),l}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(O.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await lp({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await si({appId:e,projectId:t});return{appUrl:`${he()}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Fd*60))+1)*60*1e3,Math.max(Md,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[_.BROWSERSTACK]:{name:"Browserstack"},[_.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[_.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let c=r||t.mobileApp,l=(0,sb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let m=await cp({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});return l.succeed(`app uploaded successfully to ${a}`),m.gridAppId}catch(m){throw l.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:m,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:c="",project:l,authData:{token:m=""}={},gridData:d={}}=t,{gridId:u="",type:f=""}=d;if(!c&&e.isAppFromDevice)return n;if(c){He.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:m});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else He.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:d,testRunHandler:e}),y=f===_.BROWSERSTACK||f===_.TESTIM_TVC||f===_.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:d,projectType:T});w&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var m,d;let{accessToken:n,user:i,host:o,key:a,type:c,apiUrl:l}=t;if(c===_.BROWSERSTACK){let u=`${Vs}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(c===_.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(c===_.TESTIM_HEADSPIN||c===_.TESTIM_TDC){let u=`${l}/${Ic}/apps`;return l||(u=`${c===_.TESTIM_HEADSPIN?vc:Sc}/${Ic}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(c===_.TESTIM_TVC){let u=`${Ud}/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&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(c===_.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await Lc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(d=(m=JSON.parse(h).result)==null?void 0:m.files)==null?void 0:d.some(y=>y.file===e)}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},It=new ap});function ib({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"&&!JE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function XE({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==_.TESTIM_TDC&&e.type!==_.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function YE(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function QE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===_.TESTIM_TDC,a=s===_.TESTIM_HEADSPIN,c=o?"tdc":"headspin",l=a&&O.flags.enableBatchHeadSpin.isEnabled(),m=o&&(O.flags.enableBatchTDC.isEnabled()||O.flags.headSpinTdcEnableFlagCapability.isEnabled()),d=O.flags.increaseTDCRequestTimeout.isEnabled();return{[`${c}:capture.video`]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${c}:capture.network`]:!1},...i&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:YE(t),[`${c}:enableBatch`]:l||m,...!r&&{"appium:noReset":n},...d&&{[`${c}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Na(s){return"id"in s?s.id:s.packageName}function ZE(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function eI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":n},l=n==null?void 0:n.startsWith("http");n&&!l&&(c=ZE(n,t.gridData.type));let d=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":d(),...r&&{"appium:bundleId":Na(r)},...n&&c};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":Na(r),"appium:appActivity":r.activity??".*"},...n&&c};default:throw Error(`unsupported mobile project ${s}`)}}function $r({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Na(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:Na(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function ob({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let c=QE(o.type,i,n);return eI({projectType:s,sessionCaps:c,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Fa({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 Ua({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===_.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?Rc:i.deviceNameRegex:t==="ios"&&r===_.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":Rc:".*")}function tI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function rI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ma(s,Ls)}}function ab(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function sI(s){return ab(s,e=>e.startsWith("browserstack."),"browserstack.")}function nI(s){return ab(s,e=>!e.startsWith("browserstack."))}function cb(s){return!s||!lb(s)?"2.0.0":s}function lb(s){return s.split(".")[0]==="2"||s.includes("appium2")||["latest","stable"].includes(s)}function ub({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),c=e==="android"&&(n.test(s)||a),l=e==="ios"&&o.test(s),m=c||l;if(t){let d=lb(t);return!d&&m?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):d}return m}function Ma(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}async function iI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:c}){let{osVersion:l,deviceName:m}=n,d=(a==null?void 0:a.mobile)||{},{type:u}=i,f=tI(i,s),h=await ni({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:v})=>{var E;return((E=d.staticAllocation)==null?void 0:E.deviceUdid)===v}),y=(g==null?void 0:g.osVersion)??Fa({osVersion:l,mobileConfig:d}),T=(g==null?void 0:g.name)??Ua({deviceName:m,mobileConfig:d,projectType:s,gridType:u}),w=ze(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),b={device:T,os_version:y,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":w,...c&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return $r({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:c})}function oI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{user:d,key:u,type:f}=i,h=O.flags.enableAppium2pCloudy.isEnabled(),g=Fa({osVersion:c,mobileConfig:m}),y=Ua({deviceName:l,mobileConfig:m,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),w={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:d,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...w,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Bd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=rI(b)),t="",$r({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Ls}})}function aI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{type:d}=i,u=Fa({osVersion:c,mobileConfig:m}),f=Ua({deviceName:l,mobileConfig:m,projectType:s,gridType:d}),h=(0,jr.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],ub({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},w={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:cb(g.appiumVersion??"stable"),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ma(h,Ls),"sauce:options":{...T,...w,...(0,jr.omit)(g,"appiumVersion")}};return $r({projectType:s,sessionCaps:b,appiumPrefix:Ls,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return $r({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function cI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c}){let{osVersion:l,deviceName:m}=i,d=(c==null?void 0:c.mobile)||{},{type:u}=o,f=Fa({osVersion:l,mobileConfig:d}),h=Ua({deviceName:m,mobileConfig:d,projectType:e,gridType:u}),g=sI(i.browserstack),y=(0,jr.omit)(nI(i.browserstack),["automationName","platformName","project","build","name"]),T={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`},w=O.flags.enableAppium2BrowserStack.isEnabled();if(w||ub({osVersion:y.platformVersion||f,projectType:e,isBrowserStack:!0,appiumVersion:g.appiumVersion})){let v={...T,userName:o.user,accessKey:o.key,appiumVersion:w?"2.0.1":cb(g.appiumVersion),debug:!0,networkLogs:!0},E={"appium:platformVersion":f,"appium:deviceName":h,...Ma(y,Ls),"bstack:options":{...v,...(0,jr.omit)(g,"appiumVersion")}};return $r({projectType:e,sessionCaps:E,appiumPrefix:Ls,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}let b={...T,os_version:y.platformVersion||f,device:y.deviceName||h,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...y,...Ma(g,"browserstack.")};return $r({projectType:e,sessionCaps:b,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}async function lI(s){if(_.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type)return ob(s);if(_.TESTIM_TVC===s.gridInfo.type)return await iI(s);if(_.P_CLOUDY===s.gridInfo.type)return oI(s);if(_.SAUCELABS===s.gridInfo.type)return aI(s);if(_.BROWSERSTACK===s.gridInfo.type)return cI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function uI(s,e){var l,m;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,c={};return n==="dynamic"&&(!i&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!o&&((m=r==null?void 0:r.selector)!=null&&m.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),i&&(c.manufacturer=i),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function pb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);ib({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=It.getGridConnection(e),c=await lI(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let y=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",T=uI(r,i==null?void 0:i.mobile);if(!(0,jr.isEmpty)(T)){let w=Object.entries(T).map(([b,v])=>v.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();c[`${y}:selector`]=w}}let l=e.type===_.TESTIM_TVC?{alwaysMatch:c}:c,m=O.flags.increaseTDCRequestTimeout.isEnabled(),d=0,u=(0,up.default)("2m"),f=(0,up.default)("12m"),h=Tr(O.flags.appiumConnectionRetryCount.getValue(),d),g=Tr(O.flags.appiumConnectionRequestTimeout.getValue(),u);return m&&g<f&&(g=f),{...a,desiredCapabilities:c,connectionRetryTimeout:g,capabilities:l,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function db(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;ib({nativeAppMetadata:r,appPath:i,gridInfo:t}),XE({deviceUdid:l,gridInfo:t,testRunConfig:c});let m=l||((g=(h=c.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),d=await It.getGridDirectConnection(t,m),f=ob({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return m&&(f["appium:udid"]=m),{...d,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function mb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=$r({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function fb(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 up,jr,Ls,JE,pp=S(()=>{"use strict";up=I(require("ms"));de();ae();Da();jr=require("lodash");B();oe();ge();Ls="appium:",JE=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.P_CLOUDY]});var Ba,hb=S(()=>{"use strict";Ba=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 ja,yb=S(()=>{"use strict";B();ja=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=nn;this.getLinksFromUnescapeHTML=on}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,$a,bb=S(()=>{"use strict";W();dp=P("mobile-frame-locator-mock"),$a=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,wb,Tb,Ds,mp=S(()=>{"use strict";pI=I(require("webdriverio")),wb=require("@applitools/eyes-sdk-core");hb();Xu();W();yb();Yu();we();tp();bb();rp();Tb=P("appium-test-player"),Ds=class{constructor(e,t,r,n=pI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:m}=Z(),d=new ja(this.driver);this.stepActionFactory=new l(d),_a(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new _s(aa()),this.sessionPlayer=new a(e,{tabService:new Ba,cookieUtils:void 0,FrameLocator:$a,portSelector:na,LocateElementPlayer:m,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:wb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Tb.info("appium session deleted",{...i}))}catch(o){Tb.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Z();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 Te(`${s}/api/status`)}async function vb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function Sb(s){if((await dI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Eb=S(()=>{"use strict";Ge()});var Ib={};z(Ib,{WorkerLocalTma:()=>yp});var Wr,fp,gp,hp,yp,Rb=S(()=>{"use strict";Ge();pp();Kn();B();W();Dt();mp();we();Eb();Da();Wr=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}=Z(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:c}=this.options;await Sb(o);let{project:l,authData:{token:m=""}={}}=this.options,{driver:d}=n,u=c.type,f=this.options.appId;if(f){let{mobileApp:A}=await It.getMobileAppDataByAppId({appId:f,projectId:l,token:m});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:w,version:b},v]=await Promise.all([this.getAppStateFromDevice(o,a,T),vb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Wr.info("device status and app state",{deviceStatus:v,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),Wr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let A={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=mb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),V={capabilities:{udid:a,...D}};Wr.info("requesting new appium session from TMA",{tmaSessionSettings:V,executionId:this.executionId,testResultId:this.testResultId});let x=await this.requestNewAppiumSessionFromTma(o,V,g);this.sessionData=x;let R=await d.attach({sessionId:x.sessionId,capabilities:D,options:{capabilities:D}});this.device=await It.updateTmaDeviceDetails(a,this.options,t),Wr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:R.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:R.capabilities})}catch(A){throw Wr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new hp(c):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,c=(await Te(o)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Wt(n);await Xs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new gp(l,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new fp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Z(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device,nativeApp:t.nativeApp},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((d,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:d,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw Wr.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw Wr.error("failed to run test once",{err:l}),l}}}});var Ab={};z(Ab,{WorkerAppium:()=>bp});var xb,Vr,bp,Cb=S(()=>{"use strict";B();pp();xb=require("linkedom");Kn();W();Dt();mp();we();Da();ae();fs();Vr=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,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==_.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:c}=n,l=await It.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),m=o==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let 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:d,appPath:l,androidActivityWait:m,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await It.lockDevice(i,this.options.deviceUdid),h=await db(f)):h=await pb({...f,shouldRunInEnhancedMode:a}),Vr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:d,capabilities:fb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await c.remote(h),this.device=await It.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Vr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Vr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await t.getOrientation()}catch(i){Vr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&zf(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){Vr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===_.TESTIM_HEADSPIN||i===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===_.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,c=n||"runner",l=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let m;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:v}=await It.getHeadSpinDeviceConnection(this.options.gridData,y);m=`${T}://${w}:${b}${v}`}else m=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device,nativeApp:t.nativeApp},a.playbackManager.appiumApi=new i(m,this.activeSession.sessionId,xb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Vr.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,Ae.TEST_REACHED_CUSTOM_TIMEOUT_MSG)}catch(y){throw Vr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:test"}}});var Wa,Pb=S(()=>{"use strict";B();jn();Y();Wa=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 kb(){let s=await Promise.any(mI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var mI,Va,Ga=S(()=>{"use strict";Ge();mI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];Va=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var Ob,Ha,_b=S(()=>{"use strict";Ob=I(require("ws"));B();Ga();Ha=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=Va({timeout:e}),r=new Ob.default(this._cdpUrl,t),n=Qt(o=>{r.once("open",o)}),i=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([n,i]).then(()=>r),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((c,l)=>{this._cdpCallbacks.set(i,{resolve:c,reject:l})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var za,Tp,qa,Lb=S(()=>{"use strict";B();za=I(require("chrome-launcher"));No();_b();kn();Tp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ha}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:m}=e,d=Do({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:m}),u=[...((h=d.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=d.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...za.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await za.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await vr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),gs(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},qa=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new Tp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var wp={};z(wp,{WorkerExtension:()=>ii});function fI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Db(s){return fI(s)?s:new Error(s)}var Ze,ii,Ka=S(()=>{"use strict";$e();Y();Kn();B();W();Dt();ae();Pb();Lb();ct();Ze=P("worker-ext"),ii=class extends Mt{initPlayer(){return this.options.useChromeLauncher?new qa(this.id):new Wa(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.EXTENSION})}catch(a){throw Ze.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:to(),initializedFromCache:ro(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;F("WorkerExtension runTestOnce");let o=async m=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(m.cdpTestRunner),d,Ae.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ce))throw u;return Ze.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(m,d,u)=>{try{let f=await m.url(d);return u.driverUrlFinished=!0,f}catch(f){throw Ze.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:d,urlLength:d.length}),f}},c=async m=>{let d=await e.onStarted(this.options.testStartTimeout);return m.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(F("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(y){throw Ze.warn("failed to run test via CDP",{err:y}),y}}let{driver:d}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let w=function(v){e.onCompletedCleanup(),Ze.warn("on browser closed error detected",{err:v,testResultId:r,executionId:n,testId:i}),d.unregisterToClosedBrowser(w),d.unregisterToKeepAliveFailed(b),v.type=Xr.BROWSER_CLOSED,T.abort(v)},b=function(v){d.unregisterToClosedBrowser(w),d.unregisterToKeepAliveFailed(b),Ze.warn("on keep alive failed error detected",{err:v,testResultId:r,executionId:n,testId:i}),v.type=Xr.KEEP_ALIVE_FAILED,T.abort(v)};var f=w,h=b;let y=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,y,u),c(u)]),this.options.testStartTimeout,Ae.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof ce))throw v;Ze.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let T=new AbortController;d.registerToClosedBrowser(w),d.registerToKeepAliveFailed(b);try{let v=le(e.onCompleted(),this.testRunTimeout,Ae.TEST_COMPLETE_TIMEOUT_MSG),E=await Pc(v,T.signal);d.unregisterToClosedBrowser(w),d.unregisterToKeepAliveFailed(b);try{await this.updateTestStatusOnGrid(d,Boolean(E.success),E.reason)}catch(V){Ze.error("Could not update the grid about the test status",{err:V})}d.isAlive()||(Ze.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),E.gridIssues="could not validate grid is alive");let A=d.maxKeepAliveGap();return A>=3e4&&(Ze.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),E.keepAliveIssue=A),{...E,...e.seleniumPerfStats.getStats()}}catch(v){throw Ze.warn("timeout wait until test completed",{err:v,testResultId:r,executionId:n,testId:i}),Db(v)}finally{d.unregisterToClosedBrowser(w),d.unregisterToKeepAliveFailed(b)}}catch(y){throw Ze.warn("failed to start url",{err:y}),Db(y)}};t.driver.start();try{return await super.runTestOnce(e,t),F("WorkerExtension super.runTestOnce"),await l()}catch(m){throw Ze.error("failed to run test",{err:m,testId:e.testId,resultId:e.testResultId}),m}}}});var Sp={};z(Sp,{WorkerExtensionSingleBrowser:()=>vp});var gI,hI,vp,Ep=S(()=>{"use strict";$e();B();W();$u();Dt();Ka();gI=P("base-worker"),hI=500,vp=class extends ii{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await zn(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,i){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(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,n){let i=this.handleQuarantine(t);if(i)return i;F("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await pe(hI)}}});var Ip,Ja,Nb=S(()=>{"use strict";jn();oe();$e();kl();ct();Su();Y();W();ae();Ah();qo();Ip=P("worker-manager"),Ja=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case K.SELENIUM:return(await Promise.resolve().then(()=>(op(),ip))).WorkerSelenium;case K.APPIUM:return t?(await Promise.resolve().then(()=>(Rb(),Ib))).WorkerLocalTma:(await Promise.resolve().then(()=>(Cb(),Ab))).WorkerAppium;default:return $n.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Ep(),Sp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Ka(),wp))).WorkerExtension}else switch(r){case(Mr.find(n=>n===r)&&$n.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Ep(),Sp))).WorkerExtensionSingleBrowser;case Mr.find(n=>n===r):return(await Promise.resolve().then(()=>(Ka(),wp))).WorkerExtension;case qn.find(n=>n===r):return(await Promise.resolve().then(()=>(op(),ip))).WorkerSelenium;default:throw new C(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return F("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{F("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,c){if(e&&e.length===0)return;let l=!1,m=0,d=(u,f)=>new Promise(h=>{var ie,Ie,mt,mr,k,N,$,J;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Ho(r,n,e,i,o,t),this.combinedTestResults={};let T=((ie=i.company)==null?void 0:ie.ucid)||"",w=(Ie=i.company)==null?void 0:Ie.companyId,b=(mt=i.company)==null?void 0:mt.name,v=i.source||"cli",E=i.user,A=(mr=i.company)==null?void 0:mr.planType,D=(k=i.company)==null?void 0:k.isStartUp,V=(N=i.projectData)==null?void 0:N.name,x=($=i.projectData)==null?void 0:$.type,R=i.lightweightMode,L=(J=i.gridData)==null?void 0:J.type,M=(_e,xt,ve,mc,ui,fc)=>(m++,kf({executionId:r,projectId:g,testId:xt,resultId:ve,ucid:T,companyId:w,companyName:b,projectName:V,companyPlan:A,source:v,user:E,lightweightMode:R,isStartUp:D,projectType:x,appSource:fc,gridType:L}),t.testStartAndReport(_e,r,ve,mc,ui)),H=async(_e,xt,ve,mc,ui,fc)=>{var yd,bd,Td;m--;let et={...(R==null?void 0:R.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...i.host&&{gridHost:i.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((yd=i.gridData)==null?void 0:yd.name),et.gridType=(bd=i.gridData)==null?void 0:bd.type,et.gridProvider=(Td=i.gridData)==null?void 0:Td.provider):i.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):i.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):i.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):i.browserstack?et.gridName="browserstack-from-options":i.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(_e,ve,r,mc,ui,et).catch(XT=>Ip.error("testEndAndReport threw an error",{err:XT})),ui)return;this.combinedTestResults[ve.resultId]=ve,Of({executionId:r,projectId:g,testId:xt,resultId:ve.resultId,result:ve,ucid:T,companyId:w,companyName:b,projectName:V,companyPlan:A,source:v,user:E,lightweightMode:R,logger:Ip,isStartUp:D,projectType:x,appSource:fc}),c&&!ve.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===y||l&&m===0)&&h(this.combinedTestResults)},j=(_e,xt)=>{this.combinedTestResults[xt.resultId]=xt,t.onTestIgnored(_e,xt.resultId),m--,(Object.keys(this.combinedTestResults).length===y||l&&m===0)&&h(this.combinedTestResults)},q=(_e,xt)=>t.onGridSlot(_e,xt);for(i.userData={loginData:{...Rr(),refreshToken:Zi(),authData:Rr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he()},F("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,M,H,q,j)});try{let u=await _t(),f=await eo(),h=await d(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 oi,Mb,Xa,Rp,xp,Gr,Ap=S(()=>{"use strict";oi=I(require("lodash"));B();W();oe();ae();$e();cs();Pl();kl();ge();Mb=require("uuid");Df();B();Dt();bg();Y();Nb();de();qo();({CLI_MODE:Xa}=Vt),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,n,i,o,a,c){let l={},m=new Ja(this.customExtensionLocalLocation),d=async()=>{let g=i.beforeParallel||1,y=!0,T=await m.runTests(e,c,o,a,i,n,g,y);Object.assign(l,T)},u=async()=>{let g=Si||i.parallel,y=!1;F("right before this.workerManager.runTests");let T=await m.runTests(t,c,o,a,i,n,g,y);F("right after this.workerManager.runTests"),Object.assign(l,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await m.runTests(r,c,o,a,i,n,g,y);Object.assign(l,T)};_f({executionId:o,projectId:i.project}),F("right before runBeforeTests");try{return await d(),F("right before runTestPlanTests"),await u(),F("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,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Xa.SELENIUM){let[{getSessionPlayer:v},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(we(),ir)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=v();await A.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await Op(i.project),oi.default.isEmpty(g)||!o))return;let{runKey:v,url:E}=g,A=require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}),D=1e4;await le(A.closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:v}}),D)}catch{}}}async runTestPlan(e,t,r,n,i,o,a,c){var b,v,E;let l=re(),m=n.project;Yd(l),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let d=[...e,...t,...r],u=new Ro(d,n,o,a),f=oi.default.chain(d).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:d.map(A=>A.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,m,this.startTime,i,g);F("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,l,c,h),F("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,l,i||"All Tests",u);return F("before executionEnd"),await u.executionEnd(l),F("after executionEnd"),{results:w,executionId:l,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(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(m){return oi.default.flattenDeep(Object.values(m)).reduce((d,u)=>d.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async m=>{let d=await ai(o,e.testPlan,[m],t,e.intersections);d.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=d.testPlansData[f]})}),await se(e.testPlan,async m=>{let d=await ai(o,[m],e.testPlanIds,t,e.intersections);d.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=d.testPlansData[f]})})):a=await ai(o,e.testPlan,e.testPlanIds,t,e.intersections);let c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Xa.APPIUM&&await Bu(e,r(l)),await se(c,async m=>{var h;let d=m.testPlanId;n[d]={};let u={...e};u.baseUrl||=m.startUrl,u.appId||=((h=m.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=m.gridId,e.grid&&delete u.gridId,u.gridData=await bf(e,m);let f=u.overrideExecutionName||m.name;return await se(l[d],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,d,t);Q.onTestPlanFinished(y.results,m.name,this.startTime,y.executionId,!1),n[d][y.executionId]=y.results;let T=Object.keys(n[d]).map(E=>({executionId:E,status:Uu(n[d][E])})),w=Object.keys(n[d]).map(E=>n[d][E]).reduce((E,A)=>Object.assign(E,A),{}),b=Uu(w);Object.assign(i,w);let v=b?T[0].executionId:T.find(E=>!E.status).executionId;return await kp(o,d,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var c;Rp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),F("before getSuite");let r=await Ph(e,t);if(F("after getSuite"),!((c=r==null?void 0:r.tests[0])!=null&&c.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;F("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Xa.APPIUM&&(a=await si({appId:e.appId,projectId:e.project})),await se(r.tests,async l=>{if(a&&l.forEach(d=>{"nativeApp"in d&&(d.nativeApp=a)}),e.resultId){let d=l[0];d.resultId=e.resultId,l=[d]}e.mode!==Xa.APPIUM&&await Bu(e,l),F("right before runTestPlan");let m=await this.runTestPlan([],l,[],e,i,null,t,o);return F("right after runTestPlan"),await Q.onTestPlanFinished(m.results,i,this.startTime,m.executionId,o),m})}async run(e){let t=Sn(),r=[];await this.reportTestRunnerStarted(e.project,e),tn(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=oi.default.flattenDeep(r);return F("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),F("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Gr=xp;Gr._id=(0,Mb.v4)()});var Ce={};z(Ce,{addTestRetry:()=>lu,clearTestResult:()=>Mu,deleteCloudflareTunnel:()=>Bp,fetchLambdatestConfig:()=>du,fixGridAppIDStructure:()=>lp,forceUpdateCloudflareTunnelRoutes:()=>Up,getAllGrids:()=>Cl,getAppDetails:()=>si,getApplitoolsIntegrationData:()=>Op,getBrowserStackSessionMetaData:()=>xI,getCloudflareTunnel:()=>Fp,getEditorUrl:()=>EI,getGridSlot:()=>Al,getHybridGridProvider:()=>xl,getLabFeaturesByProjectId:()=>Eu,getMobileDevicesFromGrid:()=>ni,getRealData:()=>ru,getS3Artifact:()=>Ln,getS3ArtifactText:()=>tu,getSuiteTestList:()=>ju,getTestPlan:()=>SI,getTestPlanTestList:()=>ai,getTestResults:()=>Nr,getUsageForCurrentBillingPeriod:()=>Np,initializeUserWithAuth:()=>Mp,isTestResultCompleted:()=>Nu,keepAliveCompanySlots:()=>Zl,keepAliveGrid:()=>Il,loadSfdcCredential:()=>Dp,loadTest:()=>Gn,releaseCompanySlot:()=>Yl,releaseGridSlot:()=>Rl,reportExecutionFinished:()=>xo,reportExecutionStarted:()=>cu,reportRunnerFinished:()=>Pp,reportRunnerStarted:()=>Cp,requestCompanySlot:()=>Xl,saveRemoteStep:()=>Ru,saveTestPlanResult:()=>kp,updateCompanySlot:()=>Ql,updateExecutionTests:()=>au,updateRemoteRunFailure:()=>jp,updateTestDataArtifact:()=>Ao,updateTestResult:()=>Qo,updateTestStatus:()=>Pr,uploadAppToGrid:()=>cp,uploadRunDataArtifact:()=>Fu,validateUserAccessKey:()=>Sl});async function Ns(){let s=await _t();if(!s)throw new Error("Failed to get token from server");return{[qc]:Gr.id,Authorization:`Bearer ${s}`}}async function Re({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await Ns(),o={...t,...i};return Ve({url:`${he()}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function wI(s,e,t,r={},n=void 0){let i=await Ns(),o={...r,...i};return await Xs(`${he()}${s||""}`,e,t,o,n)}async function ci(s,e){let t=await Ns();return await Dc(`${he()}${s||""}`,e,t)}async function Ub(s,e){let t=await Ns();return await Js(`${he()}${s||""}`,e,t)}async function vI(s,e){let t=await Ns();return await Ys(`${he()}${s||""}`,e||void 0,t)}async function ke(s,e,t,r){let n=await Ns();return await Te(`${he()}${s||""}`,e||void 0,n,r,t)}function Ln(s,e){return(0,ee.default)(()=>ke(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function tu(s){return(0,ee.default)(()=>vI(`/storage${s}`))}async function Cp(s,e){return await Re({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function Pp(s){return await Ub("/test-runner",{projectId:s})}async function SI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>ke("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function Dp({branch:s,projectId:e}){let t=await(0,ee.default)(()=>ke(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function Gn({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>ke(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function kp(s,e,t){return(0,ee.default)(()=>Re({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Pr(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>ci("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:yI,...i}),{retries:o,factor:1})}function au(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>ci("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:te,factor:1})}async function cu({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:m}){let{isCi:d}=await Promise.resolve().then(()=>(oo(),Af));return Re({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:m,metadata:{isCiRun:d,localRunUserId:c,isLocalRun:l}},retry:3})}function xo(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>ci("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function ai(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function ju({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:m}){return(0,ee.default)(()=>Re({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:m}}),{retries:te,factor:1})}async function si({appId:s,projectId:e}){try{return await(0,ee.default)(()=>ke(`/mobile-app/app/${s}?projectId=${e}`),{retries:te,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function Np(s){try{return await(0,ee.default)(()=>ke(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){Ft.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Nu(s,e,t){return(0,ee.default)(()=>ke(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function Nr(s,e,t,r){return(0,ee.default)(()=>ke(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function Il(s,e){return Re({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function Rl(s,e,t,r,n){return Re({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function xl(s){return Re({url:"/grid/hybrid/provider",body:s})}function Al(s){return(0,ee.default)(()=>ke("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Mp({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:m}){var d,u;try{return await(0,ee.default)(()=>Ve({url:`${he()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:m},timeout:6e4}),{retries:te,factor:1})}catch(f){if(Ft.error("error initializing info from server",f),(d=f.message)!=null&&d.includes("Bad Request"))throw new C("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 C("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(tt)return{editorUrl:tt};try{return await(0,ee.default)(()=>ke("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return Ft.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Cl(s){return(0,ee.default)(()=>ke("/grid",{companyId:s}),{retries:te,factor:1})}function ru(s,e,t){return(0,ee.default)(()=>ke(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function Qo(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function Mu(s,e,t,r){return(0,ee.default)(()=>Re({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function Ru(s,e,t,r){return(0,ee.default)(()=>Re({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,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 Bb(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,c=`${e}/${t}/${a}`,l=RI(c,TI,s),m=Buffer.from(Fb.gzip(r,{level:3})),d={file:{fileName:a,buffer:m}};return await(0,ee.default)(()=>wI(`/storage${l}`,{},d,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),l}function lu({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Re({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function Op(s){try{return await ke(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Ft.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Fp(s,e){try{return await ci("/tunnel",{companyId:s,routes:e})}catch(t){return Ft.warn("could'nt get tunnel.",{err:t}),{}}}async function Up(s,e){try{return await Re({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Ft.warn("could'nt get tunnel.",{err:t});return}}async function Bp(s,e){try{return await Ub(`/tunnel/${e}`,{companyId:s})}catch(t){Ft.warn("could'nt get tunnel.",{err:t});return}}function jp(s){return Ve({url:`${he()}/result/remoteRunFailure`,body:s})}async function ni({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${bI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>ke(i,{projectId:s}),{retries:te,factor:1})}catch(o){return Ft.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function cp({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Re({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function lp(s){return(0,ee.default)(()=>Re({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Xl(s,e){return(0,ee.default)(()=>Re({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Yl(s,e,t){return(0,ee.default)(()=>Re({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Ql(s,e,t){return(0,ee.default)(()=>ci("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Zl(s,e,t){return Re({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function xI(s,e){return await Te(`${Vs}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function Sl(s){try{return await ke("/v2/project/validateUserAccessKey",s),!0}catch(e){return Ft.error("error validating user access key",{error:e}),!1}}var _p,ur,Fb,ee,Lp,yI,Ft,te,bI,TI,du,Eu,Fu,Ao,ge=S(()=>{"use strict";_p=I(require("chalk")),ur=I(require("lodash")),Fb=I(require("pako"));B();oe();ae();Ge();ct();ee=I(require("p-retry")),Lp=I(require("object-hash"));Y();W();Ap();yI=rt(),Ft=P("testim service api"),te=3,bI="/grid",TI="test-result-artifacts";du=async(s,e)=>(0,ee.default)(()=>ke("/grid/lt/config",{companyId:s,...e&&{projectId:e}}),{retries:te,factor:1}),Eu=async s=>(0,ee.default)(()=>ke(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Fu=ur.memoize(async(s,e,t,r)=>{if(!ur.isEmpty(r))return await Bb(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Lp.default)(r)}:${e}:${t}`),Ao=ur.memoize(async(s,e,t,r,n)=>!r||ur.isEmpty(r)?void 0:await Bb(s,e,t,JSON.stringify((()=>{let o=ur.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:Vc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Lp.default)(r)}:${e}:${t}`)});function Ya(){return rt()}var $p=S(()=>{"use strict";B()});function PI(s){K.EXTENSION!==s&&process.nextTick(()=>{try{(we(),qe(ir)).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 n=r.color||"yellow",i=r.bgColor||"bgBlack";console.log(Wp.default[i](Wp.default[n](r.text)))})}function OI(s,e){let{serviceUrl:t}=s;Gs(t),Ot(async()=>s,Yr.CACHE_FN_NAME,Yr.TTL,{serviceUrl:t})(),Bt.setRegion(vg[bs(e)])}async function li(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,m=Boolean(n==null?void 0:n.general),d=Boolean(i||o),u=m?CI:AI,f=Ya(),h=jc(),g=await Hm(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!d)try{y=await kb()}catch(b){jb.error("failed to get public ip",b)}let T=!0;F("before initializeUserWithAuth");let w=await Ot(async()=>(PI(a),T=!1,await Mp({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:d,publicIp:y,gridId:c,grid:l,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:m,localGrid:d,gridId:c,grid:l,publicIp:y})();return kI(w),OI(w.clientConfig,e),s.publicIps=[w.clientPublicIp],F("after initializeUserWithAuth"),y&&w.clientPublicIp&&w.clientPublicIp!==y&&(jb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:w.clientPublicIp}),s.publicIps.push(y)),df(w.authData,{projectId:e,token:t,userAccessKey:r,publicIp:w.clientPublicIp,initializedFromCache:T}),w}var Wp,jb,AI,CI,$b=S(()=>{"use strict";Wp=I(require("chalk"));$e();ge();er();ct();Ga();ae();W();de();$p();B();os();oe();Po();jb=P("initializeUserWithAuth"),AI=1e3*60*5,CI=1e3*60*60*10});async function Gb(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Qi():s.chromeBinaryLocation,e=un({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 Er(s.playerLocation,s.canary),s.mode!==K.SELENIUM&&s.mode!==K.APPIUM&&!s.ext&&await dl(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await pl(s.installCustomExtension,n)}return await e,t}async function Hb(s){var o;_I.info("prepare MockNetwork",{location:s});let e=await Uc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Wb*1e6)throw new Error(`${Vp} exceeded ${Wb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Vp} cannot be parsed.${Qa.EOL}${a}`)}let n=new Vb.default;if(!n.validate(Zc,r)){let a=(o=n.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Qa.EOL);throw new Error(`${Vp} is malformed.${Qa.EOL}${a}`)}return r.entries}var Qa,Vb,Wb,Vp,_I,Gp=S(()=>{"use strict";Qa=I(require("node:os"));B();Im();dn();Vb=I(require("ajv"));ae();hl();W();$b();Wb=1,Vp="JSON file supplied to --mock-network-pattern",_I=P("prepare runner")});function Xb(s){return s.start&&ls(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Yb(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=Co(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 Qb=S(()=>{"use strict";Nn();us();Y()});var Ms,Kp,Zb=S(()=>{"use strict";Ms="SECRETS",Kp={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(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${r}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(n);if(l){let m=l[1];o[c]=e[m]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(n);if(l){let m=l[1];o[a]=e[m]??c}}else typeof c=="object"&&c!==null&&i(c)})};i(s)}}});var Zp={};z(Zp,{doLogin:()=>Qp,getProjectId:()=>UI,getToken:()=>BI});async function UI(){return rT("projectId")}async function BI(){return rT("token")}function tT(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 tT(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),Ce)),{editorUrl:n}=await r();bo(`${n}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${tt||hr}`)}return await e}async function Qp({overwriteExisting:s=!0,projects:e=null}={}){let t=Jp.homedir(),r=Xp.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await tT(jI(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,c.succeed(),await eT(r,i);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(m=>({title:m.name,value:m}))});i.token=l.project.ci.token,i.projectId=l.project.id,await eT(r,i);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function eT(s,e){await Yp.promises.writeFile(s,ec.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function rT(s){let e=Jp.homedir(),t=Xp.join(e,".testim"),r=await ye(t),n={};if(r)try{n=ec.parse((await Yp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Jp,Xp,ec,Yp,tc=S(()=>{"use strict";Jp=I(require("os")),Xp=I(require("path")),ec=I(require("yaml"));B();Yp=require("fs");Y();ql();oe()});var pT={};z(pT,{process:()=>XI,program:()=>p});var td,aT,rc,cT,Rt,Fe,lT,$I,Me,WI,sd,VI,GI,nT,uT,HI,rd,sc,nd,ed,Ut,iT,qI,zI,p,KI,JI,oT,XI,dT=S(()=>{"use strict";td=I(require("ms")),aT=I(require("chalk")),rc=I(require("node:fs")),cT=I(require("node:url")),Rt=I(require("lodash")),Fe=I(require("node:path"));B();Nn();Qb();er();lT=require("commander");ae();Y();Hr();B();de();Zb();qo();Po();oe();$I=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Me=(s,e)=>(e.push(s),e),WI=s=>(e,t)=>{if(t!==void 0)throw new C(`The ${s} flag can only be specified once.`);return e},sd=new lT.Command,VI=s=>s.split(","),GI=(s,e)=>!s||s.length===0?e:s,nT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],uT=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function m(g){return g.includes("--high-speed")}function d(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")}sd.help(g=>g.split(`
405
405
  `).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!o(T)&&!i(T)&&!c(T)&&!l(T)&&!m(T)&&!d(T)&&!u(T)&&!f(T)&&!h(T)).join(`
406
- `))},VI=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(aT.default.yellow(`
406
+ `))},HI=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(aT.default.yellow(`
407
407
  WARNING: ${s} is deprecated. ${t}
408
- `))},Zp=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:ec,argv:td,exit:Yp,cwd:Ft}=global.process,iT={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"}}},GI=async s=>{let e=bs(s),t=await Zc(Yr.CACHE_FN_NAME);if(t&&t.region===e){Gs(t.servicesUrl);return}let n=(iT[xt]||iT.production)[e]||{servicesUrl:"https://services.testim.io"};ec.SERVICES_HOST||Gs(n.servicesUrl)},HI=new Set(["trace","debug","info","warn","error","silent"]);Gc(td,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));ed.description("Testim.io CLI").option("-h --help","output usage information",uT).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",Me,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Me,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Me,[]).option("--test-id [test-id]","test ID to run",Me,[]).option("-l, --label [label]","labels to search test by",Me,[]).option("-n, --name [test-name]","test name to run",Me,[]).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",$I).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",Me,[]).option("--test-plan-id [test-plan-id]","test plan to run",Me,[]).option("--suite [suite-name]","suite to run",Me,[]).option("--suite-id [suite-id]","suite ID to run",Me,[]).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",Me,[]).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(ec.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,Qp.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,Qp.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: ${Zp.join("/")}`,Me,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Me,[]).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]","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]","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]","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]","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",Me,[]).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)",Me,[]).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)",Me,[]).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","").parse(td);p=ed.opts(),qI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},zI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},oT=s=>{var r;if(!O.flags.secrets.isEnabled({projectId:p.project}))return;let t=Za.readFileSync(s);(r=Hp)!=null&&r.containsSecrets(t.toString())&&Hp.injectProxySecretsStoreToGlobal()},KI=async()=>{var T,v,b,w,S,A,D,V;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!td.slice(2).length)throw uT(),new qr;if(p.version){let x="Testim CLI Version: ";ec.npm_package_version&&(console.log(x,ec.npm_package_version),Yp(0));let R=rt();R&&(console.log(x,R),Yp(0)),console.log("Could not find version, please check the package.json manually"),Yp(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Dm(),p.clearFileCache&&ns();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let x=Fe.resolve(n);_m(x)}if(p.usePrefechedData&&Nm(),p.playerRequirePath){let x=Fe.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",x);let R=Fe.join(x,"tsconfig.node.json"),M=require("ts-node").register({project:R,ignore:[/node_modules/,new RegExp(`^${Kt.escapeRegExp(Fe.relative(Ft(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:M.config.options.paths,baseUrl:M.config.options.baseUrl}),(we(),qe(ir)).options.playerPath=x;let W=require("node:module"),q=W.prototype.require;W.prototype.require=function(Ie){return Ie==="rox-alias"?q.call(this,"rox-node"):Ie==="canvas"?{}:q.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Za.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 C("missing --proxy option");if(Xb(p))return Yb(p);try{let x={};p.configFile?(oT(p.configFile),x=require(Fe.join(Ft(),p.configFile)).config):p.optionsFile&&(x=require(Fe.join(Ft(),p.optionsFile))),x&&typeof x.then=="function"&&(x=await x),Object.keys(x).forEach(R=>{let L=jI(R);p[L]=WI(p[L],x[R])})}catch(x){throw x.message=`Unable to read options file: ${x.message}`,x}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 i=((T=p.testConfig)==null?void 0:T.length)||((v=p.testConfigId)==null?void 0:v.length),o=((b=p.testPlan)==null?void 0:b.length)||((w=p.testPlanId)==null?void 0:w.length),a=((S=p.suite)==null?void 0:S.length)||((A=p.suiteId)==null?void 0:A.length);if(p.seleniumCapsFile)try{r=require(Fe.join(Ft(),p.seleniumCapsFile))}catch(x){throw new C(`Failed to parse selenium caps file file error: ${x.message}`)}if((D=p.reporters)!=null&&D.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Fe.join(Ft(),p.chromeExtraPrefs))}catch(x){throw new C(`Failed to read/open chrome extra prefs file error: ${x.message}`)}if(p.chromeExtraArgs){let x=p.chromeExtraArgs.split(",");for(let R of x){let[L]=R.split("=");nT.includes(L)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(R),L==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${L}), allowed values: ${JSON.stringify(nT)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&oT(p.paramsFile),s={...s,...require(Fe.join(Ft(),p.paramsFile))}}catch(x){throw new C(`Failed to read/open params file error: ${x.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(x){throw new C(`Failed to parse params string error: ${x.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(qI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let x=require(Fe.join(Ft(),p.sauceOptions)),R=x.platformName&&["ios","android"].includes(x.platformName.toLowerCase());if(x.browserName){let M=x.browserName.toLowerCase();switch(M){case"microsoftedge":p.browser="edge";break;default:p.browser=M}}p.browser==="edge"&&parseFloat(x.version)>=79&&(p.browser="edge-chromium");let L=parseFloat(x.version)<50&&!["dev","beta"].includes(x.version);if(!R&&p.browser==="chrome"&&L)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...x}}catch(x){throw new C(`Failed to parse saucelabs options file error: ${x.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(zI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let x=require(Fe.join(Ft(),p.browserstackOptions)),R=x.platform&&["mac","android"].includes(x.platform.toLowerCase());if(x.browserName&&(p.browser=x.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(x.browser_version)>=79&&(p.browser="edge-chromium"),!R&&parseFloat(x.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...x}}catch(x){throw new C(`Failed to parse browserstack options file error: ${x.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let x=require(Fe.join(Ft(),p.perfectoOptions)),R={location:"US East",securityToken:p.perfectoToken};p.perfecto={...R,...x}}catch(x){throw new C(`Failed to parse perfecto options file error: ${x.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let x=require(Fe.join(Ft(),p.testobjectOptions)),R={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...R,...x}}catch(x){throw new C(`Failed to parse test object options file error: ${x.message}`)}let c={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId,testStage:p.sealightsTestStage}};if(p.testOptimization=c,!p.project){let R=await(await Promise.resolve().then(()=>(Qa(),Xp))).getProjectId();if(R)p.project=R;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}GI(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 R=await(await Promise.resolve().then(()=>(Qa(),Xp))).getToken();if(R)p.token=R;else throw new C("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 d=x=>x<=0||!Number.isInteger(x);if(d(p.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new C("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 C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Nr,...Hn].includes(p.browser))throw new C(`browser ${p.browser} is not supported`);if(p.mode!==K.SELENIUM&&p.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!HI.has(p.appiumLogLevel))throw new C(`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 C("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||i||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new C("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(!o&&(p.beforeParallel!==1||p.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new C("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=cT.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(R=>R.trim()).filter(Boolean);let x=p.resultLabel.filter(R=>R.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&Tr()&&p.resultLabel.unshift(Tr()),x.length)throw new C("A result label cannot exceed 250 characters")}let f=xo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new C("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 C("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new C("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&&(a||p.name.length||p.testId.length||p.label.length||o))throw new C("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!Kt.inRange(Kt.parseInt(p.setRetention),1,11))throw new C("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 h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new C(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new C(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Kt.difference(p.codeCoverageReporter,Zp).length){let x=Kt.difference(p.codeCoverageReporter,Zp);throw new C(`invalid --code-coverage-reporter parameters ${x.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let g={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"},y=Object.keys(g).filter(x=>Boolean(p[x]));if([K.APPIUM,K.SELENIUM].includes(p.mode)&&y.length){let x=y.length>1?"are":"is";throw new C(`${y.map(R=>g[R]).join(" and ")} ${x} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let x=Za.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(x)}catch(x){throw new C(`failed to parse field file error: ${x.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new C("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(VI("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new C("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 C("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 x={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"},R=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...x,...R}}catch(x){throw new C(`failed to parse lightweightMode settings error: ${x.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 C("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"?Tr():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||f,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},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var sd,JI,Fs,dT,mT,nd,fT,gT=E(()=>{"use strict";B();Y();$();kn();sd=P("testimNgrok"),JI=".whitelisted-ngrok.testim.io",Fs="",mT=async(s,e={})=>{if(!e.ngrokToken)throw new C("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${re()}-${s.projectData.projectId}${JI}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let i=await(await ut("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(sd.info("replace https to http"),Fs=i.replace("https://","http://")):Fs=i,s.tunnelDiagnostics&&nd(),s.baseUrl=Fs},nd=async(s=!0)=>{try{let t=(await ut("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===Fs);console.log("ngrok stats",n),sd.info("ngrok stats",{tunnel:n})}catch(e){sd.error("error collecting ngrok stats",{err:e})}s&&(dT=setTimeout(()=>nd(),1e4))},fT=async s=>{if(!Fs)return;clearTimeout(dT),s.tunnelDiagnostics&&await nd(!1),await(await ut("ngrok")).disconnect(Fs)}});var pr,od,hT,YI,QI,id,tc,sc,rc,ZI,yT,bT,TT=E(()=>{"use strict";pr=I(require("os")),od=I(require("fs")),hT=I(require("child_process"));B();ge();YI="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",QI={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"}},id=pr.tmpdir(),tc=`${id}/cloudflared`,sc=null,rc=null,ZI=async()=>{if(await ye(tc))return;let e=QI[pr.platform()+pr.arch()];if(!e)throw new Error(`tunnel on ${pr.platform()+pr.arch()} platform is not supported.`);let t=e.extract?id+e.path:tc;await Je(`${YI}/${e.path}`,t),e.extract&&await ot(t,id),await od.promises.chmod(tc,"755")},yT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Dp(s.company.companyId,t),ZI()]);sc=r._id,rc=hT.spawn(tc,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Np(s.company.companyId,sc),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await od.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},bT=async s=>{let e=[];return sc&&e.push(Mp(s.company.companyId,sc)),rc&&e.push(new Promise((t,r)=>{rc.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),rc.kill()})),await Promise.all(e)}});var ad={};z(ad,{connect:()=>ic,disconnect:()=>oc,serveTunneling:()=>rR});var nc,wT,vT,tR,ic,oc,rR,cd=E(()=>{"use strict";gT();Pn();TT();ct();nc=I(require("ora"));$();ae();Po();wT=P("tunnel"),vT=s=>{var e;return[_.TESTIM_LAMBDATEST,_.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},tR=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===_.HYBRID&&s.gridData.tunnel==="cloudflare"},ic=async s=>{if(!s.tunnel)return;let e=Ir(),t;try{vT(s)?(t=(0,nc.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):tR(s)?(t=(0,nc.default)("Starting testim cloudflare tunnel...").start(),await yT(s)):(t=(0,nc.default)("Starting testim ngrok tunnel...").start(),await mT(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw r.isInvalidCredsForLT&&(n="Could not connect to LambdaTest. Check your credentials and then try again."),wT.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
410
- ${r.stdoutResult}`:n)}},oc=async s=>{if(s.tunnel)try{vT(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await bT(s):await fT(s)}catch(e){let t="catch error - failed to close tunnel";throw wT.error(t,{err:e}),new Error(t)}},rR=async(s,e=new Promise(()=>{}))=>(await ic(s),gs(()=>oc(s)),await e)});var RT={};z(RT,{init:()=>RR,run:()=>vR});async function nR(s){let e=s.project,t=await _p(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"),ls(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Hs}function oR(s,e){var i,o,a,c,l,m,d,u,f,h,g,y,T;let t=Ni(e.activePlan),r=s.parallel;if(t==="free"&&r>ET)throw new C(`The free plan allows only ${ET} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let v=(i=s.projectData)!=null&&i.type?iR[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&v?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[v]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
411
- We'll use the maximum of ${b} for now. To use more, you can adjust your command or upgrade your plan.`),s.parallel=b);let w=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.tunnel;if(s.tunnel&&!w)throw new C("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let S=(d=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:d.runInTurboMode;s.lightweightMode&&!S&&(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)===_.TESTIM_TVC){let v=e.tvcLicense.expireAt||1;if(Date.now()>v&&!e.churnedByL2C)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let b=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>b)throw new C(`Your license allows only ${b} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((g=s.gridData)==null?void 0:g.type)===_.TESTIM_TDC){let v=e.tdcLicense.expireAt||1;if(Date.now()>v)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(n){let v=(T=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:T.resultRetention;if(n>v)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${v}). Run aborted`)}if(Zt(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let v=e.tvcLicense,b=e.tdcLicense;if(v!=null&&v.isPaid||b!=null&&b.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 aR(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await nR(s)}catch(t){if([C,Hs].some(r=>t instanceof r))throw t;ld.error("could not validate cli account",{err:t})}}function cR(s){let e=Ir();return If({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function lR(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(()=>(jo(),gh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>($o(),bh));r.init(s)}}function uR(s,e){let{branch:t,autoDetect:r}=s;if(wf(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function pR(s,e){let{id:t,type:r}=e,i=IT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=vn();i&&(s.sfdcCredential=await Op({projectId:t,branch:o}))}function dR(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=Ni(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<ST?ST:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(i),O.setIsStartUp(o),O.setPlanType(a),_t.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function mR(s,e){s.editorUrl=tt||e}function fR(s,e){s.allGrids=e}function gR(s,e){s.authData=e}function hR(s,e){let{id:t,name:r,type:n,defaults:i}=e;O.setProjectId(t),O.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function yR(s){var e;s.gridData=await yf(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function bR(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function TR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(bt("user-override-file",t),s.mockNetworkRules=await Hb(s.overrideMappingFile))}async function wR(s,e){F("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await aR(s),F("in runRunner before tunnel.connect"),await ic(s),F("in runRunner after tunnel.connect");let a=await new Vr(e).run(s);return F("before tunnel.disconnect"),await oc(s),await IR(s.slotService,t,s.company.companyId),F("after tunnel.disconnect and gridService.keepAlive.end"),a}function SR(s){var e;_t.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
408
+ `))},rd=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:sc,argv:nd,exit:ed,cwd:Ut}=global.process,iT={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"}}},qI=async s=>{let e=bs(s),t=await tl(Yr.CACHE_FN_NAME);if(t&&t.region===e){Gs(t.servicesUrl);return}let n=(iT[At]||iT.production)[e]||{servicesUrl:"https://services.testim.io"};sc.SERVICES_HOST||Gs(n.servicesUrl)},zI=new Set(["trace","debug","info","warn","error","silent"]);zc(nd,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));sd.description("Testim.io CLI").option("-h --help","output usage information",uT).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",Me,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Me,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Me,[]).option("--test-id [test-id]","test ID to run",Me,[]).option("-l, --label [label]","labels to search test by",Me,[]).option("-n, --name [test-name]","test name to run",Me,[]).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",Me,[]).option("--test-plan-id [test-plan-id]","test plan to run",Me,[]).option("--suite [suite-name]","suite to run",Me,[]).option("--suite-id [suite-id]","suite ID to run",Me,[]).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",Me,[]).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(sc.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,td.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,td.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: ${rd.join("/")}`,Me,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Me,[]).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]","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]","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]","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]","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",Me,[]).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)",Me,[]).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)",Me,[]).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","").parse(nd);p=sd.opts(),KI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},JI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},oT=s=>{var r;if(!O.flags.secrets.isEnabled({projectId:p.project}))return;let t=rc.readFileSync(s);(r=Kp)!=null&&r.containsSecrets(t.toString())&&Kp.injectProxySecretsStoreToGlobal()},XI=async()=>{var T,w,b,v,E,A,D,V;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!nd.slice(2).length)throw uT(),new qr;if(p.version){let x="Testim CLI Version: ";sc.npm_package_version&&(console.log(x,sc.npm_package_version),ed(0));let R=rt();R&&(console.log(x,R),ed(0)),console.log("Could not find version, please check the package.json manually"),ed(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Mm(),p.clearFileCache&&ns();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let x=Fe.resolve(n);Dm(x)}if(p.usePrefechedData&&Fm(),p.playerRequirePath){let x=Fe.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",x);let R=Fe.join(x,"tsconfig.node.json"),M=require("ts-node").register({project:R,ignore:[/node_modules/,new RegExp(`^${Rt.escapeRegExp(Fe.relative(Ut(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:M.config.options.paths,baseUrl:M.config.options.baseUrl}),(we(),qe(ir)).options.playerPath=x;let j=require("node:module"),q=j.prototype.require;j.prototype.require=function(Ie){return Ie==="rox-alias"?q.call(this,"rox-node"):Ie==="canvas"?{}:q.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=rc.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 C("missing --proxy option");if(Xb(p))return Yb(p);try{let x={};p.configFile?(oT(p.configFile),x=require(Fe.join(Ut(),p.configFile)).config):p.optionsFile&&(x=require(Fe.join(Ut(),p.optionsFile))),x&&typeof x.then=="function"&&(x=await x),Object.keys(x).forEach(R=>{let L=$I(R);p[L]=GI(p[L],x[R])})}catch(x){throw x.message=`Unable to read options file: ${x.message}`,x}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 i=((T=p.testConfig)==null?void 0:T.length)||((w=p.testConfigId)==null?void 0:w.length),o=((b=p.testPlan)==null?void 0:b.length)||((v=p.testPlanId)==null?void 0:v.length),a=((E=p.suite)==null?void 0:E.length)||((A=p.suiteId)==null?void 0:A.length);if(p.seleniumCapsFile)try{r=require(Fe.join(Ut(),p.seleniumCapsFile))}catch(x){throw new C(`Failed to parse selenium caps file file error: ${x.message}`)}if((D=p.reporters)!=null&&D.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Fe.join(Ut(),p.chromeExtraPrefs))}catch(x){throw new C(`Failed to read/open chrome extra prefs file error: ${x.message}`)}if(p.chromeExtraArgs){let x=p.chromeExtraArgs.split(",");for(let R of x){let[L]=R.split("=");nT.includes(L)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(R),L==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${L}), allowed values: ${JSON.stringify(nT)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&oT(p.paramsFile),s={...s,...require(Fe.join(Ut(),p.paramsFile))}}catch(x){throw new C(`Failed to read/open params file error: ${x.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(x){throw new C(`Failed to parse params string error: ${x.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(KI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let x=require(Fe.join(Ut(),p.sauceOptions)),R=x.platformName&&["ios","android"].includes(x.platformName.toLowerCase());if(x.browserName){let M=x.browserName.toLowerCase();switch(M){case"microsoftedge":p.browser="edge";break;default:p.browser=M}}p.browser==="edge"&&parseFloat(x.version)>=79&&(p.browser="edge-chromium");let L=parseFloat(x.version)<50&&!["dev","beta"].includes(x.version);if(!R&&p.browser==="chrome"&&L)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...x}}catch(x){throw new C(`Failed to parse saucelabs options file error: ${x.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(JI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let x=require(Fe.join(Ut(),p.browserstackOptions)),R=x.platform&&["mac","android"].includes(x.platform.toLowerCase());if(x.browserName&&(p.browser=x.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(x.browser_version)>=79&&(p.browser="edge-chromium"),!R&&parseFloat(x.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...x}}catch(x){throw new C(`Failed to parse browserstack options file error: ${x.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let x=require(Fe.join(Ut(),p.perfectoOptions)),R={location:"US East",securityToken:p.perfectoToken};p.perfecto={...R,...x}}catch(x){throw new C(`Failed to parse perfecto options file error: ${x.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let x=require(Fe.join(Ut(),p.testobjectOptions)),R={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...R,...x}}catch(x){throw new C(`Failed to parse test object options file error: ${x.message}`)}let c={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId,testStage:p.sealightsTestStage}};if(p.testOptimization=c,!p.project){let R=await(await Promise.resolve().then(()=>(tc(),Zp))).getProjectId();if(R)p.project=R;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}qI(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 R=await(await Promise.resolve().then(()=>(tc(),Zp))).getToken();if(R)p.token=R;else throw new C("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 d=x=>x<=0||!Number.isInteger(x);if(d(p.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new C("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 C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Mr,...qn].includes(p.browser))throw new C(`browser ${p.browser} is not supported`);if(p.mode!==K.SELENIUM&&p.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!zI.has(p.appiumLogLevel))throw new C(`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 C("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||i||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new C("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(!o&&(p.beforeParallel!==1||p.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new C("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=cT.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(R=>R.trim()).filter(Boolean);let x=p.resultLabel.filter(R=>R.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&wr()&&p.resultLabel.unshift(wr()),x.length)throw new C("A result label cannot exceed 250 characters")}let f=Co(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new C("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 C("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new C("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&&(a||p.name.length||p.testId.length||p.label.length||o))throw new C("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&&!Rt.inRange(Rt.parseInt(p.setRetention),1,11))throw new C("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 h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new C(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new C(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Rt.difference(p.codeCoverageReporter,rd).length){let x=Rt.difference(p.codeCoverageReporter,rd);throw new C(`invalid --code-coverage-reporter parameters ${x.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let g={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"},y=Object.keys(g).filter(x=>Boolean(p[x]));if([K.APPIUM,K.SELENIUM].includes(p.mode)&&y.length){let x=y.length>1?"are":"is";throw new C(`${y.map(R=>g[R]).join(" and ")} ${x} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let x=rc.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(x)}catch(x){throw new C(`failed to parse field file error: ${x.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new C("--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 C("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 C(`The --label-intersection-operand flag must be one of the following values: ${Object.values(Zs).join(", ")}`);if(p.labelIntersectionOperand&&Rt.isEmpty(p.intersectWithLabel))throw new C("The --label-intersection-operand flag must be used together with the --intersect-with-label flag.");if(p.highSpeed&&(HI("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new C("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 C("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 x={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"},R=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...x,...R}}catch(x){throw new C(`failed to parse lightweightMode settings error: ${x.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 C("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"?wr():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||f,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},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var id,YI,Fs,mT,fT,od,gT,hT=S(()=>{"use strict";B();Y();W();On();id=P("testimNgrok"),YI=".whitelisted-ngrok.testim.io",Fs="",fT=async(s,e={})=>{if(!e.ngrokToken)throw new C("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${re()}-${s.projectData.projectId}${YI}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let i=await(await ut("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(id.info("replace https to http"),Fs=i.replace("https://","http://")):Fs=i,s.tunnelDiagnostics&&od(),s.baseUrl=Fs},od=async(s=!0)=>{try{let t=(await ut("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===Fs);console.log("ngrok stats",n),id.info("ngrok stats",{tunnel:n})}catch(e){id.error("error collecting ngrok stats",{err:e})}s&&(mT=setTimeout(()=>od(),1e4))},gT=async s=>{if(!Fs)return;clearTimeout(mT),s.tunnelDiagnostics&&await od(!1),await(await ut("ngrok")).disconnect(Fs)}});var pr,cd,yT,ZI,eR,ad,nc,oc,ic,tR,bT,TT,wT=S(()=>{"use strict";pr=I(require("os")),cd=I(require("fs")),yT=I(require("child_process"));B();ge();ZI="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",eR={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"}},ad=pr.tmpdir(),nc=`${ad}/cloudflared`,oc=null,ic=null,tR=async()=>{if(await ye(nc))return;let e=eR[pr.platform()+pr.arch()];if(!e)throw new Error(`tunnel on ${pr.platform()+pr.arch()} platform is not supported.`);let t=e.extract?ad+e.path:nc;await Je(`${ZI}/${e.path}`,t),e.extract&&await ot(t,ad),await cd.promises.chmod(nc,"755")},bT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Fp(s.company.companyId,t),tR()]);oc=r._id,ic=yT.spawn(nc,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Up(s.company.companyId,oc),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await cd.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},TT=async s=>{let e=[];return oc&&e.push(Bp(s.company.companyId,oc)),ic&&e.push(new Promise((t,r)=>{ic.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ic.kill()})),await Promise.all(e)}});var ld={};z(ld,{connect:()=>cc,disconnect:()=>lc,serveTunneling:()=>nR});var ac,vT,ST,sR,cc,lc,nR,ud=S(()=>{"use strict";hT();kn();wT();ct();ac=I(require("ora"));W();ae();Oo();vT=P("tunnel"),ST=s=>{var e;return[_.TESTIM_LAMBDATEST,_.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},sR=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===_.HYBRID&&s.gridData.tunnel==="cloudflare"},cc=async s=>{if(!s.tunnel)return;let e=Rr(),t;try{ST(s)?(t=(0,ac.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):sR(s)?(t=(0,ac.default)("Starting testim cloudflare tunnel...").start(),await bT(s)):(t=(0,ac.default)("Starting testim ngrok tunnel...").start(),await fT(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw r.isInvalidCredsForLT&&(n="Could not connect to LambdaTest. Check your credentials and then try again."),vT.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
410
+ ${r.stdoutResult}`:n)}},lc=async s=>{if(s.tunnel)try{ST(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await TT(s):await gT(s)}catch(e){let t="catch error - failed to close tunnel";throw vT.error(t,{err:e}),new Error(t)}},nR=async(s,e=new Promise(()=>{}))=>(await cc(s),gs(()=>lc(s)),await e)});var xT={};z(xT,{init:()=>AR,run:()=>ER});async function oR(s){let e=s.project,t=await Np(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"),ls(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Hs}function cR(s,e){var i,o,a,c,l,m,d,u,f,h,g,y,T;let t=Fi(e.activePlan),r=s.parallel;if(t==="free"&&r>IT)throw new C(`The free plan allows only ${IT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let w=(i=s.projectData)!=null&&i.type?aR[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&w?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[w]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
411
+ We'll use the maximum of ${b} for now. To use more, you can adjust your command or upgrade your plan.`),s.parallel=b);let v=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.tunnel;if(s.tunnel&&!v)throw new C("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let E=(d=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:d.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)===_.TESTIM_TVC){let w=e.tvcLicense.expireAt||1;if(Date.now()>w&&!e.churnedByL2C)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let b=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>b)throw new C(`Your license allows only ${b} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((g=s.gridData)==null?void 0:g.type)===_.TESTIM_TDC){let w=e.tdcLicense.expireAt||1;if(Date.now()>w)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(n){let w=(T=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:T.resultRetention;if(n>w)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${w}). Run aborted`)}if(Zt(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let w=e.tvcLicense,b=e.tdcLicense;if(w!=null&&w.isPaid||b!=null&&b.isPaid)return;let v=e==null?void 0:e.createdAt;if(new Date(v)<new Date(O.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let A=s.retries;A&&A>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function lR(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await oR(s)}catch(t){if([C,Hs].some(r=>t instanceof r))throw t;pd.error("could not validate cli account",{err:t})}}function uR(s){let e=Rr();return xf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function pR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(O.flags.useNewWSCLI.isEnabled()&&!e&&!t)return St.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Wo(),yh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Vo(),wh));r.init(s)}}function dR(s,e){let{branch:t,autoDetect:r}=s;if(Sf(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function mR(s,e){let{id:t,type:r}=e,i=RT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=Sn();i&&(s.sfdcCredential=await Dp({projectId:t,branch:o}))}function fR(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=Fi(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<ET?ET:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(i),O.setIsStartUp(o),O.setPlanType(a),Lt.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function gR(s,e){s.editorUrl=tt||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:n,defaults:i}=e;O.setProjectId(t),O.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function TR(s){var e;s.gridData=await Tf(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&&(Tt("user-override-file",t),s.mockNetworkRules=await Hb(s.overrideMappingFile))}async function SR(s,e){F("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await lR(s),F("in runRunner before tunnel.connect"),await cc(s),F("in runRunner after tunnel.connect");let a=await new Gr(e).run(s);return F("before tunnel.disconnect"),await lc(s),await xR(s.slotService,t,s.company.companyId),F("after tunnel.disconnect and gridService.keepAlive.end"),a}function IR(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 ER(s,e,t){s==="redis"&&xn.start(t,e),s==="mongo"&&Tn.start(e)}async function IR(s,e,t){s==="redis"&&await xn.end(t,e),s==="mongo"&&await Tn.end(e)}async function RR(s){var h,g,y,T,v,b;F("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=lR(e,{disableResults:i||Boolean((t==null?void 0:t.disableResults)&&(r||n===K.SELENIUM)),disableRemoteStep:i||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,companyByProjectId:c,projectById:l,branchName:m,allGrids:d,clientConfig:u}=await ci(s);if(c.disabled)throw new C("The company is disabled.");if(l.disabled)throw new C("The project is disabled.");if(s.printGrids){let w=d.sort((S,A)=>S.type.localeCompare(A.type));console.table(w.reduce((S,A)=>{class D{constructor(R,L){this.Type=R,this.Browsers=L}}let V=Object.entries(A.browsers||{"N/A":""}).map(x=>x.join(":")).join(", ");return S[A.name]=new D(A.type,V),S},{})),process.exit(0)}if(await o,F("after featureFlagsReady and socketConnected"),mR(s,u.editorUrl),dR(s,c),hR(s,l),bR(s,l),uR(s,m),fR(s,d),gR(s,a),await pR(s,l),await yR(s),oR(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[yg(s)]),O.flags.clearRunnerFileCache.isEnabled())try{await ns(),ld.info("runner file cache cleared")}catch(w){ld.error("failed to clear runner file cache",{err:w})}(g=s.lightweightMode)!=null&&g.disableLabs||await jn.loadLabFeatures(l.id,c.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(O.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((T=s.lightweightMode)==null?void 0:T.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`),ER(s.slotService,e,c.id),cR(e),await TR(s),SR(s);let f=vn();await Q.setOptions(s,f),(b=(v=s.testOptimization)==null?void 0:v.seaLights)!=null&&b.testStage&&s.testOptimization.seaLights.testStage!==sR&&ls(a.uid,"cli-sealights_stage_changed",{testStage:s.testOptimization.seaLights.testStage,projectId:e})}var IT,ST,ET,sR,ld,iR,vR,xT=E(()=>{"use strict";IT=I(require("lodash"));B();cd();$e();cs();fs();us();Al();ge();ct();er();$();Lt();oe();ae();Y();Ip();Uo();wu();de();In();$p();Dn();ST=30*60*1e3,ET=1,sR="Testim Automation",ld=P("runner");iR={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};vR=wR});function AT(s){s.get("/",(e,t)=>{let r=ud();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Ka()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());Jp({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var CT=E(()=>{"use strict";Qa();pd();Up()});var dd,PT,Us,ac,kT=E(()=>{"use strict";dd=I(require("chalk"));Rs();PT=require("express");$();Y();Us=P("cli-router"),ac=(0,PT.Router)();ac.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:m}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let d={stepId:r,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:m,nodePackageParams:n.nodePackageParams};try{let u=await Is(t,r,n,i,o,a,c,l,m);u.success||(console.log(dd.default.red(u.result.resultValue)),Us.error("CLI Action Failure",{message:u.result.resultValue,...d})),e.status(200).json({success:!0,data:u})}catch(u){Us.error("failed to run cli code",{err:u,...d}),console.log(dd.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});ac.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:i,stepResultId:o,timeout:a}=s.body;if(!t||typeof i!="object"||!r||typeof n!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let c={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let l=await Es(t,r,n,i,o,a);Us.info("installed packages successfully",c),e.status(200).json({success:!0,data:l})}catch(l){if(l instanceof Ct){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 OT=E(()=>{"use strict";kT()});var NT={};z(NT,{orchestrateRoutes:()=>xR});function xR(s){let e=(0,LT.default)();e.disable("x-powered-by"),s(e),e.use(md.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,DT.default)()),e.use(md.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:We||Id?"*":["http://localhost:3000","https://app.testim.io","https://app.staging.testim.io","https://app-eu.staging.testim.io","https://app.dev.testim.io","https://app-eu.dev.testim.io","https://app-eu.prod.testim.io","https://playground.testim.io","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return e.use("*",(0,_T.default)(r)),AT(e),e.use("/cliJs",ac),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var _T,LT,md,DT,MT=E(()=>{"use strict";_T=I(require("cors")),LT=I(require("express")),md=I(require("body-parser")),DT=I(require("compression"));CT();OT();oe()});var UT={};z(UT,{init:()=>AR});async function AR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(MT(),NT));return new Promise((i,o)=>{let a=()=>{};t&&(lf(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let c=n(a),l=FT.createServer(c);l.listen(s,e),l.on("error",m),l.on("listening",d);function m(u){if(u.syscall!=="listen")return o(u);switch(u.code){case"EACCES":case"EPERM":return o(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new C(`Port ${s} is already in use, is another Testim instance running?`));default:return o(u)}}function d(){let{port:u}=l.address();console.log(`Running on port: ${u}`),CR()}})}async function CR(){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 FT,BT=E(()=>{"use strict";FT=I(require("http"));ct();Y()});var qT={};z(qT,{getStartedWithStart:()=>ud,runAgentMode:()=>_R});async function _R(s){var r;let e;if(await Sr(s.playerLocation,s.canary),s.startTestimBrowser){await NR();try{e=await DR(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new C('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(BT(),UT));return e!=null&&e.webdriverApi&&setTimeout(()=>{setTimeout(()=>(ep(),qe(rb)))},6e3),t.init(s)}function ud(){return GT}function jT(s){try{return process.kill(s,0)}catch{return!1}}async function LR(s,e,t){let r=dr.join(Vt,`chrome-${mn}-process`),n=3e3,i=()=>{Oe.rmSync(r,{recursive:!0}),console.log(`
415
+ `)}function RR(s,e,t){s==="redis"&&An.start(t,e),s==="mongo"&&wn.start(e)}async function xR(s,e,t){s==="redis"&&await An.end(t,e),s==="mongo"&&await wn.end(e)}async function AR(s){var h,g,y,T,w,b;F("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=pR(e,{disableResults:i||Boolean((t==null?void 0:t.disableResults)&&(r||n===K.SELENIUM)),disableRemoteStep:i||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,companyByProjectId:c,projectById:l,branchName:m,allGrids:d,clientConfig:u}=await li(s);if(c.disabled)throw new C("The company is disabled.");if(l.disabled)throw new C("The project is disabled.");if(s.printGrids){let v=d.sort((E,A)=>E.type.localeCompare(A.type));console.table(v.reduce((E,A)=>{class D{constructor(R,L){this.Type=R,this.Browsers=L}}let V=Object.entries(A.browsers||{"N/A":""}).map(x=>x.join(":")).join(", ");return E[A.name]=new D(A.type,V),E},{})),process.exit(0)}if(await o,F("after featureFlagsReady and socketConnected"),gR(s,u.editorUrl),fR(s,c),bR(s,l),wR(s,l),dR(s,m),hR(s,d),yR(s,a),await mR(s,l),await TR(s),cR(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[Tg(s)]),O.flags.clearRunnerFileCache.isEnabled())try{await ns(),pd.info("runner file cache cleared")}catch(v){pd.error("failed to clear runner file cache",{err:v})}(g=s.lightweightMode)!=null&&g.disableLabs||await $n.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,((T=s.lightweightMode)==null?void 0:T.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`),RR(s.slotService,e,c.id),uR(e),await vR(s),IR(s);let f=Sn();await Q.setOptions(s,f),(b=(w=s.testOptimization)==null?void 0:w.seaLights)!=null&&b.testStage&&s.testOptimization.seaLights.testStage!==iR&&ls(a.uid,"cli-sealights_stage_changed",{testStage:s.testOptimization.seaLights.testStage,projectId:e})}var RT,ET,IT,iR,pd,aR,ER,AT=S(()=>{"use strict";RT=I(require("lodash"));B();ud();$e();cs();fs();us();Pl();ge();ct();er();W();Dt();oe();ae();Y();Ap();jo();Su();de();Rn();Gp();Nn();ET=30*60*1e3,IT=1,iR="Testim Automation",pd=P("runner");aR={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};ER=SR});function CT(s){s.get("/",(e,t)=>{let r=dd();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Ya()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());Qp({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var PT=S(()=>{"use strict";tc();md();$p()});var fd,kT,Us,uc,OT=S(()=>{"use strict";fd=I(require("chalk"));Rs();kT=require("express");W();Y();Us=P("cli-router"),uc=(0,kT.Router)();uc.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:m}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let d={stepId:r,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:m,nodePackageParams:n.nodePackageParams};try{let u=await Is(t,r,n,i,o,a,c,l,m);u.success||(console.log(fd.default.red(u.result.resultValue)),Us.error("CLI Action Failure",{message:u.result.resultValue,...d})),e.status(200).json({success:!0,data:u})}catch(u){Us.error("failed to run cli code",{err:u,...d}),console.log(fd.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});uc.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:i,stepResultId:o,timeout:a}=s.body;if(!t||typeof i!="object"||!r||typeof n!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let c={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let l=await Es(t,r,n,i,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 _T=S(()=>{"use strict";OT()});var MT={};z(MT,{orchestrateRoutes:()=>CR});function CR(s){let e=(0,DT.default)();e.disable("x-powered-by"),s(e),e.use(gd.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,NT.default)()),e.use(gd.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:We||xd?"*":["chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia"]};return e.use("*",(0,LT.default)(r)),CT(e),e.use("/cliJs",uc),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var LT,DT,gd,NT,FT=S(()=>{"use strict";LT=I(require("cors")),DT=I(require("express")),gd=I(require("body-parser")),NT=I(require("compression"));PT();_T();oe()});var BT={};z(BT,{init:()=>PR});async function PR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(FT(),MT));return new Promise((i,o)=>{let a=()=>{};t&&(pf(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let c=n(a),l=UT.createServer(c);l.listen(s,e),l.on("error",m),l.on("listening",d);function m(u){if(u.syscall!=="listen")return o(u);switch(u.code){case"EACCES":case"EPERM":return o(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new C(`Port ${s} is already in use, is another Testim instance running?`));default:return o(u)}}function d(){let{port:u}=l.address();console.log(`Running on port: ${u}`),kR()}})}async function kR(){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 UT,jT=S(()=>{"use strict";UT=I(require("http"));ct();Y()});var zT={};z(zT,{getStartedWithStart:()=>dd,runAgentMode:()=>DR});async function DR(s){var r;let e;if(await Er(s.playerLocation,s.canary),s.startTestimBrowser){await FR();try{e=await MR(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new C('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(jT(),BT));return e!=null&&e.webdriverApi&&setTimeout(()=>{setTimeout(()=>(sp(),qe(rb)))},6e3),t.init(s)}function dd(){return HT}function $T(s){try{return process.kill(s,0)}catch{return!1}}async function NR(s,e,t){let r=dr.join(Gt,`chrome-${fn}-process`),n=3e3,i=()=>{Oe.rmSync(r,{recursive:!0}),console.log(`
417
417
 
418
- Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(Oe.readFileSync(r));if(jT(f.pid)){let h=()=>jT(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await Xi();await ye(Bs)||await Oe.promises.mkdir(Bs,{recursive:!0});let c=[...HT(Bs,e,t,o).desiredCapabilities.chromeOptions.args,...lc.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"},m=s.extensionPath?"http://localhost:3000/app/":new URL("?startMode=true",tt||gr).href,d=await lc.launch({chromeFlags:c,startingUrl:m,ignoreDefaultFlags:!0,userDataDir:Bs,chromePath:o,envVars:l}),u={port:d.port,pid:d.pid,cdpUrl:await wr(`localhost:${d.port}`)};return Oe.writeFileSync(r,JSON.stringify(u)),d.process.once("exit",i),d.process.once("close",i),{webdriverApi:u}}async function DR(s){let e=`${mt}/testim-full-master.zip`,t=dr.basename(e),r=dr.join(Vt,t),n=dr.join(Vt,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await ye(r)){let f=await Oe.promises.stat(r);i=Date.now()-kR>f.mtimeMs}if(await Oe.promises.mkdir(Vt,{recursive:!0}),i){let f=(0,WT.default)("Downloading Testim Editor").start();await Je(e,r);try{await ot(r,n)}catch{await Oe.promises.rm(r,{recursive:!0,force:!0}),await Je(e,r);try{await ot(r,n)}catch{throw await Oe.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 Oe.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Oe.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await LR(s,o,n);await ln({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=HT(Bs,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=(Bn(),qe(Jg)),{SeleniumPerfStats:l}=(ys(),qe(ug)),m=new c;m.seleniumPerfStats=new l;let d=await m.initClient(a);GT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":tt||gr}?startMode=true`;await m.url(u),Object.assign(m,{initialUrl:u});try{m.cdpUrl=await wr(d.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:m}}function HT(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];t&&i.push(`--load-extension=${t}`);try{let o=Oo();o.length&&o.forEach(a=>i.push(`--disable-features=${a}`))}catch{}return{logLevel:PR,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function NR(){if(await ye(cc))try{let{webSocketDebuggerUrl:s}=await MR();await FR(s),await Oe.promises.unlink(cc)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Oe.promises.unlink(cc)}}async function MR(){let s=await Oe.promises.readFile(cc,{encoding:"utf8"}),[e,t]=s.split(`
419
- `).map(i=>i.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await wr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function FR(s,e=100){let t=await UR(s,e);return Qt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function UR(s,e=100){let t=ja({timeout:e}),r=new VT.default(s,t),n=Qt(o=>{r.once("open",o)}).then(()=>{r.removeAllListeners()}),i=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return Promise.race([n,i]).then(()=>r)}var $T,WT,VT,Oe,dr,lc,PR,kR,Bs,OR,cc,GT,pd=E(()=>{"use strict";$T=I(require("ms")),WT=I(require("ora")),VT=I(require("ws")),Oe=I(require("node:fs")),dr=I(require("node:path")),lc=I(require("chrome-launcher"));oe();pn();Y();fl();B();Lo();$a();PR=wi?"verbose":"silent",kR=(0,$T.default)("1h"),Bs=dr.join(Vt,"profile"),OR="DevToolsActivePort",cc=dr.join(Bs,OR);GT=!1});var $N=require("source-map-support/register");var yi=I(require("os")),$s=I(require("url")),Ws=I(require("http")),dc=I(require("https")),pi=I(require("form-data")),di=class{constructor(){this.onloadstart=null;this.onprogress=null;this.onabort=null;this.onerror=null;this.onload=null;this.ontimeout=null;this.onloadend=null;this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]||=[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let i of r)i==null||i.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},mi=class extends di{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(t!=null)if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let i=0;i<t.byteLength;i++)r[i]=n[i];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=t.byteOffset,i=new Uint8Array(t.buffer);for(let o=0;o<t.byteLength;o++)r[o]=i[o+n];this._body=r}else if(typeof t=="object"&&t instanceof pi.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}},fi=class extends Error{},gi=class extends Error{},hi=class extends Error{},mr=class extends Error{},xe=class extends di{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=dc.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 (${yi.type()} ${yi.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=xe.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new mi(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){xe.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 fi("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new hi(`HTTP method ${t} is not allowed in XHR`);let i=this._parseUrl(r);n===void 0&&(n=!0),this._method=t,this._url=i,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(xe.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!==xe.OPENED)throw new mr("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||n.startsWith("sec-")||n.startsWith("proxy-")||(r=r.toString(),n in this._loweredHeaders?(t=this._loweredHeaders[n],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[n]=t,this._headers[t]=r))}send(t){if(this.readyState!==xe.OPENED)throw new mr("XHR readyState must be OPENED");if(this._request)throw new mr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new gi(`XHR request to ${this._url.href} failed: unsupported protocol '${this._url.protocol}'. Please use supported protocols like HTTP, HTTPS, or file.`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let r=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
420
- `):""}overrideMimeType(t){if([xe.LOADING,xe.DONE].includes(this.readyState))throw new mr("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 gi("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(t){if(this._sync)throw new Error("Synchronous XHR processing not implemented");t!=null&&(this._method==="GET"||this._method==="HEAD")?t=null:t||="",this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let r=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,i=(this._url.protocol==="http:"?Ws:dc).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 pi.default&&t.pipe(i),this._request=i,this.timeout&&i.setTimeout(this.timeout,()=>this._onHttpTimeout(i)),i.on("response",o=>this._onHttpResponse(i,o)),i.on("error",()=>this._onHttpRequestError(i)),this.upload._startUpload(i),this._request===i&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof pi.default&&Object.assign(this._headers,t.getHeaders()),this._headers.Connection="keep-alive",this._headers.Host=this._url.host,this._anonymous&&(this._headers.Referer="about:blank"),this._headers["User-Agent"]=this._userAgent,this.upload._finalizeHeaders(this._headers,this._loweredHeaders)}_onHttpResponse(t,r){if(this._request!==t)return;if([301,302,303,307,308].includes(r.statusCode)){this._url=this._parseUrl(r.headers.location),this._method="GET","content-type"in this._loweredHeaders&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),"Content-Type"in this._headers&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),this._sendHxxpRequest();return}this._response=r,this._response.on("data",i=>this._onHttpResponseData(r,i)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=Ws.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(xe.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==xe.LOADING&&this._setReadyState(xe.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(xe.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(xe.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(xe.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(xe.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,n,i,o=this.nodejsBaseUrl===null?t:$s.resolve(this.nodejsBaseUrl,t),a=$s.parse(o,!1,!0);return a.hash=null,a.auth&&(i!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?i||(i=a.auth):(i||(i=a.substring(0,r)),n||(n=a.substring(r+1)))),(i||n)&&(a.auth=`${i}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let i=r.toLowerCase();this._privateHeaders[i]||(this._mimeOverride!==null&&i==="content-type"&&(n=this._mimeOverride),this._responseHeaders[i]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let i=0;i<t.length;i++)n[i]=t[i];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}},Le=xe;Le.SyntaxError=fi,Le.ProgressEvent=js,Le.SecurityError=hi,Le.XMLHttpRequest=xe,Le.InvalidStateError=mr,Le.XMLHttpRequestUpload=mi,Le.UNSENT=0,Le.OPENED=1,Le.HEADERS_RECEIVED=2,Le.LOADING=3,Le.DONE=4;Object.assign(global,{xhr2:Le,XMLHttpRequest:Le});var zT=I(require("semver"));$e();$p();er();pn();var fd=I(require("chalk")),KT=require("node:events");ae();Pn();Y();ae();no();$();var qb=I(require("os")),Wp=I(require("path")),Vp=I(require("chalk")),Xa=require("fs");oe();function zb(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=qb.homedir();(0,Xa.mkdirSync)(Wp.resolve(n,".testim_logs"),{recursive:!0});let i=Wp.resolve(n,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${i}`),Pd&&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(Vp.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(Vp.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Xa.writeFileSync)(i,`${s}
418
+ Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(Oe.readFileSync(r));if($T(f.pid)){let h=()=>$T(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await Qi();await ye(Bs)||await Oe.promises.mkdir(Bs,{recursive:!0});let c=[...qT(Bs,e,t,o).desiredCapabilities.chromeOptions.args,...dc.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"},m=s.extensionPath?"http://localhost:3000/app/":new URL("?startMode=true",tt||hr).href,d=await dc.launch({chromeFlags:c,startingUrl:m,ignoreDefaultFlags:!0,userDataDir:Bs,chromePath:o,envVars:l}),u={port:d.port,pid:d.pid,cdpUrl:await vr(`localhost:${d.port}`)};return Oe.writeFileSync(r,JSON.stringify(u)),d.process.once("exit",i),d.process.once("close",i),{webdriverApi:u}}async function MR(s){let e=`${ft}/testim-full-master.zip`,t=dr.basename(e),r=dr.join(Gt,t),n=dr.join(Gt,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await ye(r)){let f=await Oe.promises.stat(r);i=Date.now()-_R>f.mtimeMs}if(await Oe.promises.mkdir(Gt,{recursive:!0}),i){let f=(0,VT.default)("Downloading Testim Editor").start();await Je(e,r);try{await ot(r,n)}catch{await Oe.promises.rm(r,{recursive:!0,force:!0}),await Je(e,r);try{await ot(r,n)}catch{throw await Oe.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 Oe.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Oe.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await NR(s,o,n);await un({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=qT(Bs,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=(jn(),qe(Yg)),{SeleniumPerfStats:l}=(ys(),qe(dg)),m=new c;m.seleniumPerfStats=new l;let d=await m.initClient(a);HT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":tt||hr}?startMode=true`;await m.url(u),Object.assign(m,{initialUrl:u});try{m.cdpUrl=await vr(d.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:m}}function qT(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];t&&i.push(`--load-extension=${t}`);try{let o=Lo();o.length&&o.forEach(a=>i.push(`--disable-features=${a}`))}catch{}return{logLevel:OR,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function FR(){if(await ye(pc))try{let{webSocketDebuggerUrl:s}=await UR();await BR(s),await Oe.promises.unlink(pc)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Oe.promises.unlink(pc)}}async function UR(){let s=await Oe.promises.readFile(pc,{encoding:"utf8"}),[e,t]=s.split(`
419
+ `).map(i=>i.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await vr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function BR(s,e=100){let t=await jR(s,e);return Qt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function jR(s,e=100){let t=Va({timeout:e}),r=new GT.default(s,t),n=Qt(o=>{r.once("open",o)}).then(()=>{r.removeAllListeners()}),i=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return Promise.race([n,i]).then(()=>r)}var WT,VT,GT,Oe,dr,dc,OR,_R,Bs,LR,pc,HT,md=S(()=>{"use strict";WT=I(require("ms")),VT=I(require("ora")),GT=I(require("ws")),Oe=I(require("node:fs")),dr=I(require("node:path")),dc=I(require("chrome-launcher"));oe();dn();Y();hl();B();No();Ga();OR=vi?"verbose":"silent",_R=(0,WT.default)("1h"),Bs=dr.join(Gt,"profile"),LR="DevToolsActivePort",pc=dr.join(Bs,LR);HT=!1});var VN=require("source-map-support/register");var bi=I(require("os")),$s=I(require("url")),Ws=I(require("http")),gc=I(require("https")),di=I(require("form-data")),mi=class{constructor(){this.onloadstart=null;this.onprogress=null;this.onabort=null;this.onerror=null;this.onload=null;this.ontimeout=null;this.onloadend=null;this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]||=[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let i of r)i==null||i.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},fi=class extends mi{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(t!=null)if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let i=0;i<t.byteLength;i++)r[i]=n[i];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=t.byteOffset,i=new Uint8Array(t.buffer);for(let o=0;o<t.byteLength;o++)r[o]=i[o+n];this._body=r}else if(typeof t=="object"&&t instanceof di.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}},gi=class extends Error{},hi=class extends Error{},yi=class extends Error{},fr=class extends Error{},xe=class extends mi{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=gc.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 (${bi.type()} ${bi.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=xe.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new fi(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){xe.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 gi("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new yi(`HTTP method ${t} is not allowed in XHR`);let i=this._parseUrl(r);n===void 0&&(n=!0),this._method=t,this._url=i,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(xe.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!==xe.OPENED)throw new fr("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||n.startsWith("sec-")||n.startsWith("proxy-")||(r=r.toString(),n in this._loweredHeaders?(t=this._loweredHeaders[n],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[n]=t,this._headers[t]=r))}send(t){if(this.readyState!==xe.OPENED)throw new fr("XHR readyState must be OPENED");if(this._request)throw new fr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new hi(`XHR request to ${this._url.href} failed: unsupported protocol '${this._url.protocol}'. Please use supported protocols like HTTP, HTTPS, or file.`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let r=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
420
+ `):""}overrideMimeType(t){if([xe.LOADING,xe.DONE].includes(this.readyState))throw new fr("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 hi("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(t){if(this._sync)throw new Error("Synchronous XHR processing not implemented");t!=null&&(this._method==="GET"||this._method==="HEAD")?t=null:t||="",this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let r=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,i=(this._url.protocol==="http:"?Ws:gc).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 di.default&&t.pipe(i),this._request=i,this.timeout&&i.setTimeout(this.timeout,()=>this._onHttpTimeout(i)),i.on("response",o=>this._onHttpResponse(i,o)),i.on("error",()=>this._onHttpRequestError(i)),this.upload._startUpload(i),this._request===i&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof di.default&&Object.assign(this._headers,t.getHeaders()),this._headers.Connection="keep-alive",this._headers.Host=this._url.host,this._anonymous&&(this._headers.Referer="about:blank"),this._headers["User-Agent"]=this._userAgent,this.upload._finalizeHeaders(this._headers,this._loweredHeaders)}_onHttpResponse(t,r){if(this._request!==t)return;if([301,302,303,307,308].includes(r.statusCode)){this._url=this._parseUrl(r.headers.location),this._method="GET","content-type"in this._loweredHeaders&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),"Content-Type"in this._headers&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),this._sendHxxpRequest();return}this._response=r,this._response.on("data",i=>this._onHttpResponseData(r,i)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=Ws.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(xe.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==xe.LOADING&&this._setReadyState(xe.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(xe.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(xe.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(xe.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(xe.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,n,i,o=this.nodejsBaseUrl===null?t:$s.resolve(this.nodejsBaseUrl,t),a=$s.parse(o,!1,!0);return a.hash=null,a.auth&&(i!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?i||(i=a.auth):(i||(i=a.substring(0,r)),n||(n=a.substring(r+1)))),(i||n)&&(a.auth=`${i}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let i=r.toLowerCase();this._privateHeaders[i]||(this._mimeOverride!==null&&i==="content-type"&&(n=this._mimeOverride),this._responseHeaders[i]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let i=0;i<t.length;i++)n[i]=t[i];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}},Le=xe;Le.SyntaxError=gi,Le.ProgressEvent=js,Le.SecurityError=yi,Le.XMLHttpRequest=xe,Le.InvalidStateError=fr,Le.XMLHttpRequestUpload=fi,Le.UNSENT=0,Le.OPENED=1,Le.HEADERS_RECEIVED=2,Le.LOADING=3,Le.DONE=4;Object.assign(global,{xhr2:Le,XMLHttpRequest:Le});var KT=I(require("semver"));$e();Gp();er();dn();var hd=I(require("chalk")),JT=require("node:events");ae();kn();Y();ae();oo();W();var qb=I(require("os")),Hp=I(require("path")),qp=I(require("chalk")),Za=require("fs");oe();function zb(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=qb.homedir();(0,Za.mkdirSync)(Hp.resolve(n,".testim_logs"),{recursive:!0});let i=Hp.resolve(n,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${i}`),Od&&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(qp.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(qp.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Za.writeFileSync)(i,`${s}
421
421
  ${s==null?void 0:s.stack}
422
422
 
423
- ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}an();var LI=P("process-handler"),Kb=!1;function DI(s){return s instanceof Error?1:Kb?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(fe.SKIPPED)||[t,i].includes(fe.FAILED)&&n===Xe.EVALUATING?!1:r!==!0)?1:0)}function NI(){try{tr("chromedriver").stop()}catch{}}function Jb(){Kb=!0}async function Gp(s){s!=null&&s.stack&&(ps?console.error(s,s.stack):zb(s)),NI(),await LI.waitForFlush(),process.exit(DI(s))}ge();$();de();rd();var BR=P("cli-entry");function jR(s){if(!zT.satisfies(process.version,s))throw new C(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=20,t=22,r=Number(process.versions.node.split(".")[0]),n=new Date("2026-04-30T00:00:00.000Z"),i=n<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new C(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&i)throw new C(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(fd.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function $R(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(B(),X)),Promise.resolve().then(()=>(rd(),pT))]);F("Starting Testim.io CLI"),zf(Gp);try{jR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await O.fetch({proxy:p.proxy});let t=await e.process();if(F("in main, after options.process"),Yd(global.proxyUri),KT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,Xd(t.project),Lm("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:i}=await Promise.resolve().then(()=>(kn(),Yf));return await i()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await ns(),await ci(t);let{preloadTests:i}=await Promise.resolve().then(()=>(Fo(),lh));await i(t),!t.playerRequirePath&&t.mode!==K.EXTENSION&&await Sr(t.playerLocation,t.canary);let o=await Om();o.success?console.log(`created prefetched data at ${$i()}`):console.error("failed to create prefetch data",o.error);return}let r=await Promise.resolve().then(()=>(xT(),RT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:i}=await Promise.resolve().then(()=>(cd(),ad));await i(t);return}if(s.isAgentMode(t)){let{runAgentMode:i}=await Promise.resolve().then(()=>(pd(),qT));return i(t)}if(t.saveRCALocally){let{initServer:i}=await Promise.resolve().then(()=>(su(),fg)),{port:o}=await i(t);t.localRCASaver=`http://localhost:${o}`}t.exitCodeIgnoreFailingTests&&Jb(),F("right before testRunner.init/prepareRunner.prepare"),await r.init(t);let n=await Gb(t);return F("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof qr)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Fp({...r,error:t.message}).catch(()=>{}),t instanceof C?(console.log(fd.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),BR.error("runner ended with unexpected error",{err:t}),t)}}$R().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),Gp(s)});
423
+ ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}cn();var DI=P("process-handler"),Kb=!1;function NI(s){return s instanceof Error?1:Kb?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(fe.SKIPPED)||[t,i].includes(fe.FAILED)&&n===Xe.EVALUATING?!1:r!==!0)?1:0)}function MI(){try{tr("chromedriver").stop()}catch{}}function Jb(){Kb=!0}async function zp(s){s!=null&&s.stack&&(ps?console.error(s,s.stack):zb(s)),MI(),await DI.waitForFlush(),process.exit(NI(s))}ge();W();de();var $R=P("cli-entry");function WR(s){if(!KT.satisfies(process.version,s))throw new C(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=20,t=22,r=Number(process.versions.node.split(".")[0]),n=new Date("2026-04-30T00:00:00.000Z"),i=n<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new C(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&i)throw new C(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(hd.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function VR(){console.log("Starting Testim.io CLI");let s=await Promise.resolve().then(()=>(B(),X));F("Starting Testim.io CLI"),Jf(zp);try{WR(s.getEnginesVersion())}catch(e){console.log("Argument Error:",e.message),process.exit(1)}try{let e=await Promise.resolve().then(()=>(dT(),pT)),{program:t}=e;await O.fetch({proxy:t.proxy});let r=await e.process();if(F("in main, after options.process"),Zd(global.proxyUri),JT.EventEmitter.defaultMaxListeners="parallel"in r&&r.parallel>10?r.parallel*3:30,Qd(r.project),Nm("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(()=>(On(),Zf));return await o()}if(s.isLoginMode(r))return;if(s.isCreatePrefetchedDataMode(r)){await ns(),await li(r);let{preloadTests:o}=await Promise.resolve().then(()=>(Bo(),ph));await o(r),!r.playerRequirePath&&r.mode!==K.EXTENSION&&await Er(r.playerLocation,r.canary);let a=await Lm();a.success?console.log(`created prefetched data at ${Vi()}`):console.error("failed to create prefetch data",a.error);return}let n=await Promise.resolve().then(()=>(AT(),xT));if(s.isTunnelOnlyMode(r)){await n.init(r);let{serveTunneling:o}=await Promise.resolve().then(()=>(ud(),ld));await o(r);return}if(s.isAgentMode(r)){let{runAgentMode:o}=await Promise.resolve().then(()=>(md(),zT));return o(r)}if(r.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(iu(),hg)),{port:a}=await o(r);r.localRCASaver=`http://localhost:${a}`}r.exitCodeIgnoreFailingTests&&Jb(),F("right before testRunner.init/prepareRunner.prepare"),await n.init(r);let i=await Gb(r);return F("right after testRunner.init/prepareRunner.prepare"),await n.run(r,i)}catch(e){if(e instanceof qr)return;let t=s.getArgsOnRemoteRunFailure();return t&&await jp({...t,error:e.message}).catch(()=>{}),e instanceof C?(console.log(hd.default.red("Argument Error:",e.message)),e):(console.log("Error:",e.message),$R.error("runner ended with unexpected error",{err:e}),e)}}VR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),zp(s)});
424
424
  //# sourceMappingURL=cli.js.map