@testim/testim-cli 4.146.0 → 4.147.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,27 +1,27 @@
1
1
  #! /usr/bin/env node
2
- "use strict";var FT=Object.create;var ii=Object.defineProperty;var BT=Object.getOwnPropertyDescriptor;var jT=Object.getOwnPropertyNames;var $T=Object.getPrototypeOf,WT=Object.prototype.hasOwnProperty;var v=(s,e)=>()=>(s&&(e=s(s=0)),e);var H=(s,e)=>{for(var t in e)ii(s,t,{get:e[t],enumerable:!0})},cd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of jT(e))!WT.call(s,n)&&n!==t&&ii(s,n,{get:()=>e[n],enumerable:!(r=BT(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?FT($T(s)):{},cd(e||!s||!s.__esModule?ii(t,"default",{value:s,enumerable:!0}):t,s)),He=s=>cd(ii({},"__esModule",{value:!0}),s);var Be={};H(Be,{log:()=>M,measure:()=>GT});function M(...s){if(!ud)return;let e=Date.now();console.log(`${e-VT} ${e-ld} `,...s),ld=e}function GT(s,e){if(!ud)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var ud,VT,ld,je=v(()=>{"use strict";ud=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,VT=Date.now(),ld=Date.now()});var Gt,jr=v(()=>{"use strict";Gt="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 qe(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 tc(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function Oe(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 rc=v(()=>{"use strict"});var nc,pd,dd,mi=v(()=>{nc={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},pd={"@applitools/eyes-sdk-core":"13.11.34-legacy.1","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"2.1.3","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.3",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",express:"4.21.1",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"1.1.4",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"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.40.6",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},dd={node:">= 18.0.0"}});var Ls,zT,md,Ht,KT,Ds,fd,gd,fi,Ns,hd,he,yd,bd,gi,$e,ic,Td,hi,wd,MR,UR,vd,Sd,Ms,Ed,Id,Rd,xd,oc,ac,cc,lc,Ad,Us,Cd,uc,de=v(()=>{"use strict";Ls=process.env.SERVICES_HOST||"https://services.testim.io",zT="https://testimstatic.blob.core.windows.net",md="https://tstresultfiles.azureedge.net";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:Ls,Ls=process.env.SERVICES_HOST);Ht=process.env.RUNNER_ENVIRONMENT||"production",KT={production:"",staging:".staging",development:".dev"},Ds=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${KT[Ht]}.testim.io`,fd=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),gd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),fi=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Ns=process.env.EDITOR_URL,hd=process.env.WEBSOCKET_HOST||`${Ls}/ws`,he=Ls,yd=parseInt(process.env.LOGGER_CONSOLE||"0",10),bd=parseInt(process.env.LOGGER_DEBUG||"0",10),gi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),$e=parseInt(process.env.IS_ON_PREM||"0",10),ic=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Td=parseInt(process.env.DEBUG_MODE||"0",10),hi=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,wd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",MR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),UR=process.env.APPIUM_VERSION||"1.10.1",vd=process.env.GATEWAY_URL,Sd=process.env.EXTENSION_SERVICES_HOST||Ls,Ms=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:zT,Ed=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:md,Id=md,Rd=5*60*1e3,xd=40,oc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",ac=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",cc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",lc=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Ad=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Us=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Cd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,uc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var Pd,yi,kd=v(()=>{"use strict";Pd=I(require("superagent")),yi=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=process.env.CORALOGIX_PRIVATE_KEY||"d0eb01da-f966-1663-63c6-8871225d7c39",this.applicationName=e.applicationName,this.subsystemName=e.subsystemName,this.flushIntervalMs=e.flushIntervalMs||2e3,this.maxBufferedLogsCount=e.maxBufferedLogsCount||50,this.interval=setInterval(()=>this.flushLogs(),this.flushIntervalMs)}addLog(e){this.logs.push(e),this.logs.length>=this.maxBufferedLogsCount&&this.flushLogs()}setProxy(e){this.proxy=e}async waitForFlush(){clearInterval(this.interval),await this.flushLogs()}async flushLogs(){try{if(this.logs.length===0)return;let e={applicationName:this.applicationName,subsystemName:this.subsystemName,logEntries:[...this.logs]};this.logs=[];let t=Pd.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={};H(_d,{CoralogixTransport:()=>pc});var Od,JT,YT,pc,Ld=v(()=>{"use strict";Od=I(require("winston-transport"));kd();JT={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},YT=["err","error","reason","e"],pc=class extends Od.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new yi({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...l}=t,c={...a,...l},d={severity:JT[i],text:o,category:n||this.category};c.className&&(d.className=c.className),c.methodName&&(d.methodName=c.methodName),c.threadId&&(d.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let m=!1;a instanceof Error&&(m=!0,c.msg=a.message+a.stack,o&&(c.msg=`${o}
3
- ${c.msg}`));for(let u of YT)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(o&&!m&&(c.msg=o),d.text=JSON.stringify(c)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function ZT(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!$e){let{CoralogixTransport:r}=(Ld(),He(_d)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(yd){let r={depth:5,colors:!0};s.push(new mt.transports.Console({format:mt.format.combine(mt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),mt.format.timestamp({format:"HH:mm:ss:SSS"}),mt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ti.inspect(n.meta,r)}`))}))}return[s,e,t]}function jd(s){dc=s}function $d(s){Bd=s}function Wd(s){$e||!s||rw(s)}function Nd(s){return{projectId:Bd,time:new Date().toISOString(),...dc&&!s&&{executionId:dc}}}function P(s){return new mc(iw.child({category:s}))}var Md,mt,Ti,bi,Ud,XT,QT,Dd,Fd,ew,tw,rw,sw,nw,iw,dc,Bd,mc,W=v(()=>{"use strict";Md=I(require("node:os")),mt=I(require("winston"));de();Ti=I(require("node:util")),bi=I(require("chalk")),Ud=I(require("dayjs"));F();XT=Md.hostname(),QT=tt();Dd={depth:5,colors:!0},Fd=(s,e,t)=>{let r=`[${(0,Ud.default)().format("HH:mm:ss:SSS")}]`,n=Ti.inspect(e,Dd),i=Ti.inspect(t,Dd);return`${bi.default.white(r)} ${bi.default.reset()}SessionPlayer-${bi.default.red(s)} ${n} ${i}`},[ew,tw,rw]=ZT(),sw=bd?"debug":"info",nw={release:Boolean(!1),branch:"runner-v4.146.0"},iw=mt.createLogger({levels:mt.config.syslog.levels,level:sw,transports:ew,defaultMeta:{name:"runner",hostname:XT,nodeVersion:process.version,runnerVersion:QT,...nw}}),dc=null,Bd=null;mc=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Nd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Nd(n)})}catch{}}}waitForFlush(){return tw()}}});var Ei,$r,C,qt,pr,It,wi,Wr,oe,Fs,rt,zt,Rt,vi,Vr,Si,Bs,Y=v(()=>{"use strict";Ei=require("p-retry"),$r=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},qt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},pr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},It=class extends Ei.AbortError{},wi=class extends Ei.AbortError{},Wr=class extends Ei.AbortError{},oe=class extends Error{},Fs=class extends Error{},rt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},zt=class extends rt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Rt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},vi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Vr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Si=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Bs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function fc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ce(s){return(0,Hd.setTimeout)(s)}function gc(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"){fi&&!Vd&&(Vd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new oe(t);return e=fi?Number(fi)||6e5:e,Promise.race([s,ce(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Gd||=(await import("p-limit")).default;let r=Gd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Kt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Hd,Vd,Gd,hc=v(()=>{"use strict";Hd=require("timers/promises");Y();de();Vd=!1});var $s,qd,aw,js,zd,cw,lw,Kd,Jd=v(()=>{"use strict";$s=I(require("lodash"));de();qd=require("dns");W();hc();aw=P("http-request-counters"),js=!1,zd=async()=>{if($e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>qd.promises.lookup(t)));return e||(js=!0),e}catch{return aw.error("network connectivity test failed"),js=!0,!1}},cw=$s.throttle(zd,10*1e3),lw=60*1e3*15,Kd=()=>{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)},lw)}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),js||cw(),a}}}async function r(){if(js||!await zd())return!1;let n=$s.sum([...s.fail.values()]),i=$s.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>js,t}});var ze={};H(ze,{deleteReq:()=>Ws,didNetworkConnectivityTestFail:()=>Ec,download:()=>vc,get:()=>Te,getFullRes:()=>fw,getText:()=>Gs,head:()=>gw,isNetworkHealthy:()=>Sc,post:()=>We,postForm:()=>Vs,postText:()=>Tc,put:()=>wc});function pw(){return global.caFileContent}function dw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function mw(){return!ft.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(ft.default),global.proxyUri}function dr(s,e=!1){let t=pw();t&&s.ca(t);let r=!e&&mw();r&&s.proxy(r)}async function Yd(s,e,t={},r=Gr,n=0){let i=ft.default.post(s).send(e).timeout(r).set(t);dr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function bc(s,e,t={},r=Gr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=ft.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),dr(o,i),await o}var ft,yc,st,Gr,uw,Dt,Ws,We,Vs,Gs,Tc,Te,fw,gw,wc,vc,Sc,Ec,Ve=v(()=>{"use strict";ft=I(require("superagent"));W();Jd();yc=P("http-request"),st=Kd(),Gr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,uw=6e4;Dt=(s,e,t)=>{let r=e.response;e.response instanceof ft.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 yc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Ws=st(async(s,e={},t={},r=Gr)=>{try{let n=ft.default.delete(s).send(e).timeout(r).set(t);dr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Dt("failed to delete request",n,{url:s})}}),We=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await Yd(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});Vs=st(async(s,e,t,r={},n=Gr)=>{let i=ft.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)}),dr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});Gs=st(async(s,e,t)=>{try{return(await bc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),Tc=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Yd(s,e,t,r,n)).text}catch(i){return Dt("failed to post request",i,{url:s})}}),Te=st(async(s,e,t,r,n)=>{try{return(await bc(s,e,t,r,n)).body}catch(i){return Dt("failed to get request",i,{url:s,query:e})}}),fw=st((s,e,t,r)=>bc(s,e,t,r)),gw=st(async s=>{let e=ft.default.head(s).timeout(Gr);dr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),wc=st(async(s,e,t={},r=Gr)=>{let n=ft.default.put(s).send(e).timeout(r).set(t);dr(n);try{return(await n).body}catch(i){return Dt("failed to put request",i,{url:s})}}),vc=st(async s=>{yc.info("start to download",{url:s});let e=ft.default.get(s).set("User-Agent","Testim.io").timeout(uw).buffer(!0).parse(dw);dr(e);try{let t=await e;return yc.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),Sc=st.isNetworkHealthy,Ec=st.didNetworkConnectivityTestFail});function gt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Nt.resolve(__dirname,"../../"):s=Nt.resolve(__dirname,""),s):process.cwd()}function Ii(s,e){return Oe(s)?e||Nt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Nt.basename(s)}function tt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function xc(){try{return dd.node}catch{return""}}async function Zd(s,e,t=!0){let r=await nt.promises.readdir(s,{withFileTypes:!0});await nt.promises.mkdir(e,{recursive:t});for(let n of r){let i=Nt.join(s,n.name),o=Nt.join(e,n.name);n.isDirectory()?await Zd(i,o):await nt.promises.copyFile(i,o)}}async function ye(s){try{return await nt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Nt,Xd,Qd,nt,hw,Mt,Ke,Ri,Ic,it,Rc,em=v(()=>{"use strict";Nt=I(require("node:path"));rc();mi();Xd=I(require("unzip-stream")),Qd=I(require("p-retry")),nt=require("node:fs"),hw=3;Mt=async s=>{let e=await Promise.resolve().then(()=>(Ve(),ze));return(0,Qd.default)(()=>e.download(s),{retries:hw,factor:1})},Ke=async(s,e)=>{let t=await Mt(s);return nt.promises.writeFile(e,t.body)};Ri=async(s,e)=>{let t=Ii(s,e);return Oe(s)?Ke(s,t):nt.promises.copyFile(s,t)},Ic=async s=>Oe(s)?Mt(s):nt.promises.readFile(s),it=async(s,e)=>(0,nt.createReadStream)(s).pipe(Xd.Extract({path:e})),Rc=s=>(0,nt.statSync)(s).size/1e6});var Ut={};H(Ut,{APPIUM_SESSION_MESSAGE:()=>Oc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>xi,MOBILE_RUN_SKIP_REASON:()=>kc,X_HEADER_RUNNER_ID:()=>_c,gridMessages:()=>ht,gridTypes:()=>L,mobileWeb:()=>Cc,runnerStatus:()=>Ac,runnerTestStatus:()=>me,socketEventTypes:()=>xt,stepResult:()=>qs,test:()=>Pc,testRunStatus:()=>Hs,testStatus:()=>Je,timeoutMessages:()=>Me});var Me,Hs,Ac,me,Je,ht,Cc,Pc,xt,q,L,qs,xi,kc,Oc,_c,ie=v(()=>{"use strict";Me={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Hs={COMPLETED:"completed"},Ac={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Je={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ht={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Cc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Pc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},xt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},L={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},qs={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"},xi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},kc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Oc={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"},_c="X-Testim-Runner-ID"});function zs(s,e){var t,r,n;return(t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(i=>{var o;return(o=i.runConfig)==null?void 0:o.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function yw(){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 Ks,tm,Ye,bw,Tw,ww,vw,Sw,Lc,Dc,rm=v(()=>{"use strict";ie();Ks=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},tm=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Je.QUARANTINE&&!tm(e)&&!e.runQuarantinedTests;bw=s=>Boolean(s.loginMode),Tw=s=>Boolean(s.tunnelOnlyMode),ww=s=>Boolean(s.createPrefechedData),vw=s=>Boolean(s.installLazyDepsMode),Sw=s=>Boolean(s.agentMode),Lc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Dc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Ci(s=0){return Ai.default.duration(s).format("HH:mm:ss.SSS")}function Nc(s=0){return Ai.default.duration(s).asSeconds()}var Ai,sm,nm=v(()=>{"use strict";Ai=I(require("dayjs")),sm=I(require("dayjs/plugin/duration"));Ai.default.extend(sm.default)});var Js,Hr,Jt,im,qr,om=v(()=>{"use strict";ie();Js=s=>!(!s||"fileName"in s),Hr=(s,e)=>{if(e===L.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Jt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},im=s=>s===L.TESTIM_TVC,qr=(s,e)=>im(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Mc(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 am=v(()=>{"use strict"});var J={};H(J,{OSS:()=>zr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>tc,calcPercentile:()=>Oi,copyDir:()=>Zd,delay:()=>ce,doesPathExist:()=>ye,download:()=>Mt,downloadAndSave:()=>Ke,extractElementId:()=>_e,getArgsOnRemoteRunFailure:()=>yw,getBrowserInfo:()=>Iw,getCdpAddressForHost:()=>gr,getCliLocation:()=>gt,getDuration:()=>Ci,getDurationSec:()=>Nc,getEnginesVersion:()=>xc,getEnvironmentGitBranch:()=>fr,getLinksFromUnescapeHTML:()=>Qs,getLocalFileSizeInMB:()=>Rc,getMemorySnapshot:()=>Mc,getPlanType:()=>ki,getRunConfigByBrowserName:()=>Ys,getRunnerVersion:()=>tt,getSource:()=>Ri,getSourceAsBuffer:()=>Ic,getSourcePath:()=>Ii,getTestUrl:()=>qe,getUniqBrowsers:()=>zs,groupTestsByRetries:()=>Fc,guid:()=>re,hasTestPlanFlag:()=>Ks,isAgentMode:()=>Sw,isAppFromDevice:()=>Js,isAppFromDeviceDisabled:()=>qr,isCreatePrefetchedDataMode:()=>ww,isInstallLazyDepsMode:()=>vw,isLoginMode:()=>bw,isMobileProject:()=>Jt,isPromise:()=>fc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>tm,isTestimVirtualGrid:()=>im,isTunnelOnlyMode:()=>Tw,isURL:()=>Oe,promiseAbort:()=>gc,promiseFromCallback:()=>Kt,promiseMap:()=>se,promiseTimeout:()=>le,removePropertyFromObject:()=>Pi,replaceArgsWithNoDashes:()=>Lc,sanitizeNumberValue:()=>mr,shouldBlockVirtualIosBuild:()=>Hr,spreadObjectToArgs:()=>Dc,unescapeHTML:()=>Xs,unzipFile:()=>it});function mr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function Iw(s){return s=s.toLowerCase(),Uc.find(e=>e.browserValue===s)}function Ys(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Uc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Uc[0],n=zr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=zr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=zr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=zr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=zr.find(i=>i.bs.platform===t.platform))),Kr.merge(r,n)}function fr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Pi(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Pi(s[r],e,t))}function _e(s){return s.ELEMENT||s[Gt]}function ki(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Fc(s=[]){return Kr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=Kr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Xs(s){return pm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Qs(s){return[...pm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function gr(s,e){let t=await Promise.resolve().then(()=>(Ve(),ze));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 cm,Kr,lm,um,Ew,Ft,zr,Uc,Oi,pm,F=v(()=>{"use strict";cm=I(require("os")),Kr=I(require("lodash")),lm=I(require("path")),um=require("linkedom");jr();em();rm();nm();rc();hc();om();am();Ew=cm.homedir(),Ft=lm.join(Ew,".testim-browser-profile"),zr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Uc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Oi=(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]};pm=new um.DOMParser});var Bc={};H(Bc,{$schema:()=>Rw,default:()=>kw,definitions:()=>xw,properties:()=>Pw,required:()=>Cw,type:()=>Aw});var Rw,xw,Aw,Cw,Pw,kw,dm=v(()=>{Rw="http://json-schema.org/draft-07/schema#",xw={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}}}},Aw="object",Cw=["entries"],Pw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},kw={$schema:Rw,definitions:xw,type:Aw,required:Cw,properties:Pw}});async function Tm(){try{return await le(_i.promises.readFile(Mi()).then(async s=>{let e=await bm;return Lw(e,s)}),3e4)}catch{return{}}}function Lw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=Yr.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 Bt(s,e,t=Ow,r=void 0){return async()=>{if(!gm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Dw(e);if(i)return Zs.debug("cache hit:",{fnName:e}),i;if(Zs.debug("cache miss:",{fnName:e}),!hm)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 Nw(e,o,t),o}}async function Dw(s){let t=(await Ui)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Nw(s,e,t){if(jc)throw Zs.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 Ui;r[s]={value:e,expiry:Date.now()+t},ym=new Promise(n=>{Ni=n}),_w(r)}catch{Zs.error("failed updating cache")}}async function Xr(){let s=await Ui;Object.keys(s).forEach(e=>{delete s[e]})}function wm(s){gm=s}function Mw(s=!0){hm=s}async function vm(){try{return jc=!0,await ym}finally{jc=!1}}function Sm(s){Di=s,Ui=Tm()}var _i,Li,Yr,mm,Zs,Di,fm,Ni,gm,hm,jc,ym,bm,Ow,Mi,Ui,_w,Em,Im,mx,Rm,Yt=v(()=>{"use strict";_i=I(require("fs")),Li=I(require("path")),Yr=I(require("crypto"));F();mm=require("lodash");W();Zs=P("local cache"),Di=Li.resolve(gt(),"testim-cache"),gm=!0,hm=!0,jc=!1,ym=new Promise(s=>{Ni=s}),bm=new Promise(s=>{fm=s}),Ow=1e3*60*60*3,Mi=()=>Li.resolve(Li.resolve(Di,"testim.cache"));Ui=Tm(),_w=(0,mm.debounce)(async s=>{let e;try{let t=await bm,r=Yr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=Yr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Di)||await _i.promises.mkdir(Di,{recursive:!0}),await _i.promises.writeFile(Mi(),a)}catch(t){Zs.error("failed saving cache",{err:t}),e=t}Ni(e?{success:!1,error:e}:{success:!0})},200);Em=fm,Im=wm.bind(void 0,!1),mx=wm.bind(void 0,!0),Rm=()=>Mw(!1)});function Fi(){return{cliLocation:gt(),userInfo:Qr.userInfo(),platform:Qr.platform(),release:Qr.release()}}var Qr,$c=v(()=>{"use strict";Qr=I(require("node:os"));F()});function Uw(s){try{return Bi.resolve(Bi.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 Xt(s){let e=Uw(s);return require(e)}var Bi,en=v(()=>{"use strict";Bi=I(require("path"))});function Fw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Bw(s){return/The "to" argument must be of type string./.exec(s)}function Pm(s,e,t){let r=Fw(s),n=Bw(s);return r||n?(Cm.info("Failed to install package due to insufficient write access",{...Fi(),package:t,path:r}),console.error(`
2
+ "use strict";var jT=Object.create;var ii=Object.defineProperty;var $T=Object.getOwnPropertyDescriptor;var WT=Object.getOwnPropertyNames;var VT=Object.getPrototypeOf,GT=Object.prototype.hasOwnProperty;var v=(s,e)=>()=>(s&&(e=s(s=0)),e);var H=(s,e)=>{for(var t in e)ii(s,t,{get:e[t],enumerable:!0})},ld=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of WT(e))!GT.call(s,n)&&n!==t&&ii(s,n,{get:()=>e[n],enumerable:!(r=$T(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?jT(VT(s)):{},ld(e||!s||!s.__esModule?ii(t,"default",{value:s,enumerable:!0}):t,s)),He=s=>ld(ii({},"__esModule",{value:!0}),s);var Be={};H(Be,{log:()=>M,measure:()=>qT});function M(...s){if(!pd)return;let e=Date.now();console.log(`${e-HT} ${e-ud} `,...s),ud=e}function qT(s,e){if(!pd)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var pd,HT,ud,je=v(()=>{"use strict";pd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,HT=Date.now(),ud=Date.now()});var Gt,jr=v(()=>{"use strict";Gt="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 qe(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 tc(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function Oe(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 rc=v(()=>{"use strict"});var nc,dd,md,mi=v(()=>{nc={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},dd={"@applitools/eyes-sdk-core":"13.11.34-legacy.1","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"2.1.3","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.3",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6",express:"4.21.1",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"1.1.4",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2","node-fetch":"2.7.0",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"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.40.6",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},md={node:">= 18.0.0"}});var Ls,JT,fd,Ht,YT,Ds,gd,hd,fi,Ns,yd,he,bd,Td,gi,$e,ic,wd,hi,vd,FR,BR,Sd,Ed,Ms,Id,Rd,xd,Ad,oc,ac,cc,lc,Cd,Us,Pd,uc,de=v(()=>{"use strict";Ls=process.env.SERVICES_HOST||"https://services.testim.io",JT="https://testimstatic.blob.core.windows.net",fd="https://tstresultfiles.azureedge.net";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:Ls,Ls=process.env.SERVICES_HOST);Ht=process.env.RUNNER_ENVIRONMENT||"production",YT={production:"",staging:".staging",development:".dev"},Ds=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${YT[Ht]}.testim.io`,gd=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),hd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),fi=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Ns=process.env.EDITOR_URL,yd=process.env.WEBSOCKET_HOST||`${Ls}/ws`,he=Ls,bd=parseInt(process.env.LOGGER_CONSOLE||"0",10),Td=parseInt(process.env.LOGGER_DEBUG||"0",10),gi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),$e=parseInt(process.env.IS_ON_PREM||"0",10),ic=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,wd=parseInt(process.env.DEBUG_MODE||"0",10),hi=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,vd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",FR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),BR=process.env.APPIUM_VERSION||"1.10.1",Sd=process.env.GATEWAY_URL,Ed=process.env.EXTENSION_SERVICES_HOST||Ls,Ms=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:JT,Id=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:fd,Rd=fd,xd=5*60*1e3,Ad=40,oc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",ac=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",cc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",lc=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Cd=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Us=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Pd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,uc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var kd,yi,Od=v(()=>{"use strict";kd=I(require("superagent")),yi=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=process.env.CORALOGIX_PRIVATE_KEY||"d0eb01da-f966-1663-63c6-8871225d7c39",this.applicationName=e.applicationName,this.subsystemName=e.subsystemName,this.flushIntervalMs=e.flushIntervalMs||2e3,this.maxBufferedLogsCount=e.maxBufferedLogsCount||50,this.interval=setInterval(()=>this.flushLogs(),this.flushIntervalMs)}addLog(e){this.logs.push(e),this.logs.length>=this.maxBufferedLogsCount&&this.flushLogs()}setProxy(e){this.proxy=e}async waitForFlush(){clearInterval(this.interval),await this.flushLogs()}async flushLogs(){try{if(this.logs.length===0)return;let e={applicationName:this.applicationName,subsystemName:this.subsystemName,logEntries:[...this.logs]};this.logs=[];let t=kd.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 Ld={};H(Ld,{CoralogixTransport:()=>pc});var _d,XT,QT,pc,Dd=v(()=>{"use strict";_d=I(require("winston-transport"));Od();XT={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},QT=["err","error","reason","e"],pc=class extends _d.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new yi({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...l}=t,c={...a,...l},d={severity:XT[i],text:o,category:n||this.category};c.className&&(d.className=c.className),c.methodName&&(d.methodName=c.methodName),c.threadId&&(d.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let m=!1;a instanceof Error&&(m=!0,c.msg=a.message+a.stack,o&&(c.msg=`${o}
3
+ ${c.msg}`));for(let u of QT)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(o&&!m&&(c.msg=o),d.text=JSON.stringify(c)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function tw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!$e){let{CoralogixTransport:r}=(Dd(),He(Ld)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(bd){let r={depth:5,colors:!0};s.push(new mt.transports.Console({format:mt.format.combine(mt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),mt.format.timestamp({format:"HH:mm:ss:SSS"}),mt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ti.inspect(n.meta,r)}`))}))}return[s,e,t]}function $d(s){dc=s}function Wd(s){jd=s}function Vd(s){$e||!s||nw(s)}function Md(s){return{projectId:jd,time:new Date().toISOString(),...dc&&!s&&{executionId:dc}}}function P(s){return new mc(aw.child({category:s}))}var Ud,mt,Ti,bi,Fd,ZT,ew,Nd,Bd,rw,sw,nw,iw,ow,aw,dc,jd,mc,W=v(()=>{"use strict";Ud=I(require("node:os")),mt=I(require("winston"));de();Ti=I(require("node:util")),bi=I(require("chalk")),Fd=I(require("dayjs"));F();ZT=Ud.hostname(),ew=tt();Nd={depth:5,colors:!0},Bd=(s,e,t)=>{let r=`[${(0,Fd.default)().format("HH:mm:ss:SSS")}]`,n=Ti.inspect(e,Nd),i=Ti.inspect(t,Nd);return`${bi.default.white(r)} ${bi.default.reset()}SessionPlayer-${bi.default.red(s)} ${n} ${i}`},[rw,sw,nw]=tw(),iw=Td?"debug":"info",ow={release:Boolean(!1),branch:"runner-v4.147.0"},aw=mt.createLogger({levels:mt.config.syslog.levels,level:iw,transports:rw,defaultMeta:{name:"runner",hostname:ZT,nodeVersion:process.version,runnerVersion:ew,...ow}}),dc=null,jd=null;mc=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Md(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Md(n)})}catch{}}}waitForFlush(){return sw()}}});var Ei,$r,C,qt,pr,It,wi,Wr,oe,Fs,rt,zt,Rt,vi,Vr,Si,Bs,Y=v(()=>{"use strict";Ei=require("p-retry"),$r=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},qt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},pr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},It=class extends Ei.AbortError{},wi=class extends Ei.AbortError{},Wr=class extends Ei.AbortError{},oe=class extends Error{},Fs=class extends Error{},rt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},zt=class extends rt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Rt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},vi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Vr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Si=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Bs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function fc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ce(s){return(0,qd.setTimeout)(s)}function gc(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"){fi&&!Gd&&(Gd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new oe(t);return e=fi?Number(fi)||6e5:e,Promise.race([s,ce(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Hd||=(await import("p-limit")).default;let r=Hd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Kt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var qd,Gd,Hd,hc=v(()=>{"use strict";qd=require("timers/promises");Y();de();Gd=!1});var $s,zd,lw,js,Kd,uw,pw,Jd,Yd=v(()=>{"use strict";$s=I(require("lodash"));de();zd=require("dns");W();hc();lw=P("http-request-counters"),js=!1,Kd=async()=>{if($e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>zd.promises.lookup(t)));return e||(js=!0),e}catch{return lw.error("network connectivity test failed"),js=!0,!1}},uw=$s.throttle(Kd,10*1e3),pw=60*1e3*15,Jd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},pw)}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),js||uw(),a}}}async function r(){if(js||!await Kd())return!1;let n=$s.sum([...s.fail.values()]),i=$s.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>js,t}});var ze={};H(ze,{deleteReq:()=>Ws,didNetworkConnectivityTestFail:()=>Ec,download:()=>vc,get:()=>Te,getFullRes:()=>hw,getText:()=>Gs,head:()=>yw,isNetworkHealthy:()=>Sc,post:()=>We,postForm:()=>Vs,postText:()=>Tc,put:()=>wc});function mw(){return global.caFileContent}function fw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function gw(){return!ft.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(ft.default),global.proxyUri}function dr(s,e=!1){let t=mw();t&&s.ca(t);let r=!e&&gw();r&&s.proxy(r)}async function Xd(s,e,t={},r=Gr,n=0){let i=ft.default.post(s).send(e).timeout(r).set(t);dr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function bc(s,e,t={},r=Gr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=ft.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),dr(o,i),await o}var ft,yc,st,Gr,dw,Dt,Ws,We,Vs,Gs,Tc,Te,hw,yw,wc,vc,Sc,Ec,Ve=v(()=>{"use strict";ft=I(require("superagent"));W();Yd();yc=P("http-request"),st=Jd(),Gr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,dw=6e4;Dt=(s,e,t)=>{let r=e.response;e.response instanceof ft.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 yc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Ws=st(async(s,e={},t={},r=Gr)=>{try{let n=ft.default.delete(s).send(e).timeout(r).set(t);dr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Dt("failed to delete request",n,{url:s})}}),We=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await Xd(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});Vs=st(async(s,e,t,r={},n=Gr)=>{let i=ft.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)}),dr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});Gs=st(async(s,e,t)=>{try{return(await bc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),Tc=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Xd(s,e,t,r,n)).text}catch(i){return Dt("failed to post request",i,{url:s})}}),Te=st(async(s,e,t,r,n)=>{try{return(await bc(s,e,t,r,n)).body}catch(i){return Dt("failed to get request",i,{url:s,query:e})}}),hw=st((s,e,t,r)=>bc(s,e,t,r)),yw=st(async s=>{let e=ft.default.head(s).timeout(Gr);dr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),wc=st(async(s,e,t={},r=Gr)=>{let n=ft.default.put(s).send(e).timeout(r).set(t);dr(n);try{return(await n).body}catch(i){return Dt("failed to put request",i,{url:s})}}),vc=st(async s=>{yc.info("start to download",{url:s});let e=ft.default.get(s).set("User-Agent","Testim.io").timeout(dw).buffer(!0).parse(fw);dr(e);try{let t=await e;return yc.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),Sc=st.isNetworkHealthy,Ec=st.didNetworkConnectivityTestFail});function gt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Nt.resolve(__dirname,"../../"):s=Nt.resolve(__dirname,""),s):process.cwd()}function Ii(s,e){return Oe(s)?e||Nt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Nt.basename(s)}function tt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function xc(){try{return md.node}catch{return""}}async function em(s,e,t=!0){let r=await nt.promises.readdir(s,{withFileTypes:!0});await nt.promises.mkdir(e,{recursive:t});for(let n of r){let i=Nt.join(s,n.name),o=Nt.join(e,n.name);n.isDirectory()?await em(i,o):await nt.promises.copyFile(i,o)}}async function ye(s){try{return await nt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Nt,Qd,Zd,nt,bw,Mt,Ke,Ri,Ic,it,Rc,tm=v(()=>{"use strict";Nt=I(require("node:path"));rc();mi();Qd=I(require("unzip-stream")),Zd=I(require("p-retry")),nt=require("node:fs"),bw=3;Mt=async s=>{let e=await Promise.resolve().then(()=>(Ve(),ze));return(0,Zd.default)(()=>e.download(s),{retries:bw,factor:1})},Ke=async(s,e)=>{let t=await Mt(s);return nt.promises.writeFile(e,t.body)};Ri=async(s,e)=>{let t=Ii(s,e);return Oe(s)?Ke(s,t):nt.promises.copyFile(s,t)},Ic=async s=>Oe(s)?Mt(s):nt.promises.readFile(s),it=async(s,e)=>(0,nt.createReadStream)(s).pipe(Qd.Extract({path:e})),Rc=s=>(0,nt.statSync)(s).size/1e6});var Ut={};H(Ut,{APPIUM_SESSION_MESSAGE:()=>Oc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>xi,MOBILE_RUN_SKIP_REASON:()=>kc,X_HEADER_RUNNER_ID:()=>_c,gridMessages:()=>ht,gridTypes:()=>L,mobileWeb:()=>Cc,runnerStatus:()=>Ac,runnerTestStatus:()=>me,socketEventTypes:()=>xt,stepResult:()=>qs,test:()=>Pc,testRunStatus:()=>Hs,testStatus:()=>Je,timeoutMessages:()=>Me});var Me,Hs,Ac,me,Je,ht,Cc,Pc,xt,q,L,qs,xi,kc,Oc,_c,ie=v(()=>{"use strict";Me={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Hs={COMPLETED:"completed"},Ac={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Je={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ht={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Cc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Pc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},xt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},L={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},qs={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"},xi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},kc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Oc={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"},_c="X-Testim-Runner-ID"});function zs(s,e){var t,r,n;return(t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(i=>{var o;return(o=i.runConfig)==null?void 0:o.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function Tw(){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 Ks,rm,Ye,ww,vw,Sw,Ew,Iw,Lc,Dc,sm=v(()=>{"use strict";ie();Ks=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},rm=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Je.QUARANTINE&&!rm(e)&&!e.runQuarantinedTests;ww=s=>Boolean(s.loginMode),vw=s=>Boolean(s.tunnelOnlyMode),Sw=s=>Boolean(s.createPrefechedData),Ew=s=>Boolean(s.installLazyDepsMode),Iw=s=>Boolean(s.agentMode),Lc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Dc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Ci(s=0){return Ai.default.duration(s).format("HH:mm:ss.SSS")}function Nc(s=0){return Ai.default.duration(s).asSeconds()}var Ai,nm,im=v(()=>{"use strict";Ai=I(require("dayjs")),nm=I(require("dayjs/plugin/duration"));Ai.default.extend(nm.default)});var Js,Hr,Jt,om,qr,am=v(()=>{"use strict";ie();Js=s=>!(!s||"fileName"in s),Hr=(s,e)=>{if(e===L.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Jt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},om=s=>s===L.TESTIM_TVC,qr=(s,e)=>om(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Mc(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 cm=v(()=>{"use strict"});var J={};H(J,{OSS:()=>zr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>tc,calcPercentile:()=>Oi,copyDir:()=>em,delay:()=>ce,doesPathExist:()=>ye,download:()=>Mt,downloadAndSave:()=>Ke,extractElementId:()=>_e,getArgsOnRemoteRunFailure:()=>Tw,getBrowserInfo:()=>xw,getCdpAddressForHost:()=>gr,getCliLocation:()=>gt,getDuration:()=>Ci,getDurationSec:()=>Nc,getEnginesVersion:()=>xc,getEnvironmentGitBranch:()=>fr,getLinksFromUnescapeHTML:()=>Qs,getLocalFileSizeInMB:()=>Rc,getMemorySnapshot:()=>Mc,getPlanType:()=>ki,getRunConfigByBrowserName:()=>Ys,getRunnerVersion:()=>tt,getSource:()=>Ri,getSourceAsBuffer:()=>Ic,getSourcePath:()=>Ii,getTestUrl:()=>qe,getUniqBrowsers:()=>zs,groupTestsByRetries:()=>Fc,guid:()=>re,hasTestPlanFlag:()=>Ks,isAgentMode:()=>Iw,isAppFromDevice:()=>Js,isAppFromDeviceDisabled:()=>qr,isCreatePrefetchedDataMode:()=>Sw,isInstallLazyDepsMode:()=>Ew,isLoginMode:()=>ww,isMobileProject:()=>Jt,isPromise:()=>fc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>rm,isTestimVirtualGrid:()=>om,isTunnelOnlyMode:()=>vw,isURL:()=>Oe,promiseAbort:()=>gc,promiseFromCallback:()=>Kt,promiseMap:()=>se,promiseTimeout:()=>le,removePropertyFromObject:()=>Pi,replaceArgsWithNoDashes:()=>Lc,sanitizeNumberValue:()=>mr,shouldBlockVirtualIosBuild:()=>Hr,spreadObjectToArgs:()=>Dc,unescapeHTML:()=>Xs,unzipFile:()=>it});function mr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function xw(s){return s=s.toLowerCase(),Uc.find(e=>e.browserValue===s)}function Ys(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Uc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Uc[0],n=zr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=zr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=zr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=zr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=zr.find(i=>i.bs.platform===t.platform))),Kr.merge(r,n)}function fr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Pi(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Pi(s[r],e,t))}function _e(s){return s.ELEMENT||s[Gt]}function ki(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Fc(s=[]){return Kr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=Kr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Xs(s){return dm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Qs(s){return[...dm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function gr(s,e){let t=await Promise.resolve().then(()=>(Ve(),ze));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 lm,Kr,um,pm,Rw,Ft,zr,Uc,Oi,dm,F=v(()=>{"use strict";lm=I(require("os")),Kr=I(require("lodash")),um=I(require("path")),pm=require("linkedom");jr();tm();sm();im();rc();hc();am();cm();Rw=lm.homedir(),Ft=um.join(Rw,".testim-browser-profile"),zr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Uc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Oi=(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]};dm=new pm.DOMParser});var Bc={};H(Bc,{$schema:()=>Aw,default:()=>_w,definitions:()=>Cw,properties:()=>Ow,required:()=>kw,type:()=>Pw});var Aw,Cw,Pw,kw,Ow,_w,mm=v(()=>{Aw="http://json-schema.org/draft-07/schema#",Cw={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}}}},Pw="object",kw=["entries"],Ow={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},_w={$schema:Aw,definitions:Cw,type:Pw,required:kw,properties:Ow}});async function wm(){try{return await le(_i.promises.readFile(Mi()).then(async s=>{let e=await Tm;return Nw(e,s)}),3e4)}catch{return{}}}function Nw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=Yr.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 Bt(s,e,t=Lw,r=void 0){return async()=>{if(!hm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Mw(e);if(i)return Zs.debug("cache hit:",{fnName:e}),i;if(Zs.debug("cache miss:",{fnName:e}),!ym)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Uw(e,o,t),o}}async function Mw(s){let t=(await Ui)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Uw(s,e,t){if(jc)throw Zs.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 Ui;r[s]={value:e,expiry:Date.now()+t},bm=new Promise(n=>{Ni=n}),Dw(r)}catch{Zs.error("failed updating cache")}}async function Xr(){let s=await Ui;Object.keys(s).forEach(e=>{delete s[e]})}function vm(s){hm=s}function Fw(s=!0){ym=s}async function Sm(){try{return jc=!0,await bm}finally{jc=!1}}function Em(s){Di=s,Ui=wm()}var _i,Li,Yr,fm,Zs,Di,gm,Ni,hm,ym,jc,bm,Tm,Lw,Mi,Ui,Dw,Im,Rm,gx,xm,Yt=v(()=>{"use strict";_i=I(require("fs")),Li=I(require("path")),Yr=I(require("crypto"));F();fm=require("lodash");W();Zs=P("local cache"),Di=Li.resolve(gt(),"testim-cache"),hm=!0,ym=!0,jc=!1,bm=new Promise(s=>{Ni=s}),Tm=new Promise(s=>{gm=s}),Lw=1e3*60*60*3,Mi=()=>Li.resolve(Li.resolve(Di,"testim.cache"));Ui=wm(),Dw=(0,fm.debounce)(async s=>{let e;try{let t=await Tm,r=Yr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=Yr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Di)||await _i.promises.mkdir(Di,{recursive:!0}),await _i.promises.writeFile(Mi(),a)}catch(t){Zs.error("failed saving cache",{err:t}),e=t}Ni(e?{success:!1,error:e}:{success:!0})},200);Im=gm,Rm=vm.bind(void 0,!1),gx=vm.bind(void 0,!0),xm=()=>Fw(!1)});function Fi(){return{cliLocation:gt(),userInfo:Qr.userInfo(),platform:Qr.platform(),release:Qr.release()}}var Qr,$c=v(()=>{"use strict";Qr=I(require("node:os"));F()});function Bw(s){try{return Bi.resolve(Bi.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 Xt(s){let e=Bw(s);return require(e)}var Bi,en=v(()=>{"use strict";Bi=I(require("path"))});function jw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function $w(s){return/The "to" argument must be of type string./.exec(s)}function km(s,e,t){let r=jw(s),n=$w(s);return r||n?(Pm.info("Failed to install package due to insufficient write access",{...Fi(),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 Gc(s){try{return Xt(s)}catch{return!1}}function km(s,e){return require(yr.join(s,`./node_modules/${e}/package.json`)).version}function Om(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=Om(s[e]);if(t)return t}}function _m(s){let e=require(yr.join(s,"package.json"));if(!("exports"in e))return"";let t=Om(e);if(!t)throw new Si(e.name);return t}async function $i(s,e,t){let r=yr.join(s,"npm-shrinkwrap.json"),n=yr.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await ye(r)&&(await Vc.promises.rename(r,n),i=!0)}catch{}return await Am(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw Pm(o.stderr,s,e)?new Vr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await Vc.promises.rename(n,r)}catch{}}}function Hc(s,e,t,r,n=!0){return new Promise((i,o)=>{let a=t?["--proxy",t]:[],l=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},c="",d="",m=["--no-save","--no-package-lock","--no-prune","--no-audit","--progress=false"];n&&m.push("--prefer-offline");let u=(0,ji.spawn)("node",[Wc,"i","--prefix",s,...m,...e,...a],l);u.stderr.pipe(process.stderr),u.stdout.pipe(process.stdout),u.stdout.on("data",f=>{c+=f}),u.stderr.on("data",f=>{d+=f}),u.on("close",f=>{var h,g;if(f){n&&Hc(s,e,t,r,!1).then(i).catch(o);let y;try{let T=(h=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(d))==null?void 0:h[1],w=(g=/No matching version found for (\S+)@/gm.exec(d))==null?void 0:g[1];T||w?y=`404 Not Found - GET https://registry.npmjs.org/${w??T} - Not found`:Pm(d,Wc)?y=`insufficient write access in location ${Wc}`:y=`Npm Installation closed with exit code ${f} with error: ${d}`}catch{y=`Npm Install closed with exit code ${f}
10
- stdout: ${c} stderr: ${d}`}Cm.info(`Npm Install closed with exit code ${f}`,{message:y,stderr:d}),o(new Rt(y))}else i(c)}),setTimeout(()=>{try{u.kill()}finally{o(new oe)}},r)})}async function Lm(){try{return(await Am("npm -v")).stdout.trim()}catch{return""}}var Vc,yr,xm,ji,Am,Cm,Wc,Zr=v(()=>{"use strict";Vc=I(require("fs")),yr=I(require("path"));F();xm=require("util"),ji=require("child_process");W();$c();en();Y();Am=(0,xm.promisify)(ji.exec),Cm=P("cli-service");Wc=yr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var U,Nm,jw,$w,Ww,Dm,Wi,zc,_,ue=v(()=>{"use strict";U=I(require("rox-node"));W();F();de();Nm=P("FeatureFlagsService"),jw=!$e&&!0&&!vd,$w=2e4,Ww=60*60*24,Dm=["labs","disabled","enabled"],Wi=class extends U.default.RoxString{constructor(e="disabled"){super(e,Dm)}getValue(){let e=super.getValue();return Dm.includes(e)?e:(Nm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},zc=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 Wi("labs"),highSpeedMode:new Wi,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("",[]),useStepResultIdForStepTransactions:new U.default.Flag,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},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(){if(!jw)return;let e={fetchIntervalInSec:Ww,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return le(U.default.setup(wd,e),$w).catch(t=>Nm.error("failed to get feature flag status",t))}},_=new zc});var Bm={};H(Bm,{install:()=>Gw,isReady:()=>qw,start:()=>Hw});var Mm,Um,Fm,Jc,Kc,Vw,Gw,Hw,qw,jm=v(()=>{"use strict";Mm=I(require("fkill")),Um=I(require("p-retry"));Zr();Ve();F();en();ue();Fm="chromedriver",Jc=9515,Kc=`http://localhost:${Jc}/wd/hub`,Vw=[`--port=${Jc}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],Gw=async()=>{let s=_.flags.chromedriverCdnBinariesUrl.getValue(),e=Oe(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await $i(gt(),`${Fm} --detect_chromedriver_version ${e}`)},Hw=async()=>{process.env.NODE_OPTIONS="",await(0,Mm.default)(`:${Jc}`,{silent:!0}),await Xt(Fm).start(Vw,!0)},qw=async({chromeBinaryLocation:s})=>{await(0,Um.default)(async()=>{var n;let e=await Te(`${Kc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await We({url:`${Kc}/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 Ws(`${Kc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var rn={};H(rn,{getSessionPlayerFolder:()=>Zc,prepareChromeDriver:()=>tn,prepareCustomExtension:()=>Xc,prepareExtension:()=>Qc,preparePlayer:()=>br});async function Xc(s,e=!1){if(!s)return;if(Oe(s)){let n=es.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await zw(s)>Yc&&!e)throw new C($m);return await Ke(s,n),n}let t=es.resolve(s);if(!Vm.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(Rc(t)>Yc&&!e)throw new C($m);return t}async function zw(s){let e=(Ve(),He(ze));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Vi.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function Qc(s){Vi.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Ii(t)}));return Bt(()=>se(e,({location:t,path:r})=>Ri(t,r)),"prepareExtension",Hm,e)()}async function tn(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(jm(),Bm));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 Vr||(Vi.error(a,{...s,...Fi(),error:(0,Gm.serializeError)(o)}),console.log(`
9
+ `),!0):!1}function Gc(s){try{return Xt(s)}catch{return!1}}function Om(s,e){return require(yr.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 Lm(s){let e=require(yr.join(s,"package.json"));if(!("exports"in e))return"";let t=_m(e);if(!t)throw new Si(e.name);return t}async function $i(s,e,t){let r=yr.join(s,"npm-shrinkwrap.json"),n=yr.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await ye(r)&&(await Vc.promises.rename(r,n),i=!0)}catch{}return await Cm(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw km(o.stderr,s,e)?new Vr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await Vc.promises.rename(n,r)}catch{}}}function Hc(s,e,t,r,n=!0){return new Promise((i,o)=>{let a=t?["--proxy",t]:[],l=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},c="",d="",m=["--no-save","--no-package-lock","--no-prune","--no-audit","--progress=false"];n&&m.push("--prefer-offline");let u=(0,ji.spawn)("node",[Wc,"i","--prefix",s,...m,...e,...a],l);u.stderr.pipe(process.stderr),u.stdout.pipe(process.stdout),u.stdout.on("data",f=>{c+=f}),u.stderr.on("data",f=>{d+=f}),u.on("close",f=>{var h,g;if(f){n&&Hc(s,e,t,r,!1).then(i).catch(o);let y;try{let T=(h=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(d))==null?void 0:h[1],w=(g=/No matching version found for (\S+)@/gm.exec(d))==null?void 0:g[1];T||w?y=`404 Not Found - GET https://registry.npmjs.org/${w??T} - Not found`:km(d,Wc)?y=`insufficient write access in location ${Wc}`:y=`Npm Installation closed with exit code ${f} with error: ${d}`}catch{y=`Npm Install closed with exit code ${f}
10
+ stdout: ${c} stderr: ${d}`}Pm.info(`Npm Install closed with exit code ${f}`,{message:y,stderr:d}),o(new Rt(y))}else i(c)}),setTimeout(()=>{try{u.kill()}finally{o(new oe)}},r)})}async function Dm(){try{return(await Cm("npm -v")).stdout.trim()}catch{return""}}var Vc,yr,Am,ji,Cm,Pm,Wc,Zr=v(()=>{"use strict";Vc=I(require("fs")),yr=I(require("path"));F();Am=require("util"),ji=require("child_process");W();$c();en();Y();Cm=(0,Am.promisify)(ji.exec),Pm=P("cli-service");Wc=yr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var U,Mm,Um,Fm,Ww,Vw,Gw,Nm,Wi,zc,_,ue=v(()=>{"use strict";U=I(require("rox-node")),Mm=I(require("node-fetch")),Um=require("eventsource");W();F();de();Fm=P("FeatureFlagsService"),Ww=!$e&&!0&&!Sd,Vw=2e4,Gw=60*60*24,Nm=["labs","disabled","enabled"],Wi=class extends U.default.RoxString{constructor(e="disabled"){super(e,Nm)}getValue(){let e=super.getValue();return Nm.includes(e)?e:(Fm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},zc=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 Wi("labs"),highSpeedMode:new Wi,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("",[]),useStepResultIdForStepTransactions:new U.default.Flag,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},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(!Ww)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,l)=>(0,Mm.default)(a,{...l,agent:o}),n=function(a){return new Um.EventSource(a,{fetch:r})}}let i={fetchIntervalInSec:Gw,fetchFunction:r,eventSourceImpl:n};return le(U.default.setup(vd,i),Vw).catch(o=>Fm.error("failed to get feature flag status",o))}},_=new zc});var Wm={};H(Wm,{install:()=>qw,isReady:()=>Kw,start:()=>zw});var Bm,jm,$m,Jc,Kc,Hw,qw,zw,Kw,Vm=v(()=>{"use strict";Bm=I(require("fkill")),jm=I(require("p-retry"));Zr();Ve();F();en();ue();$m="chromedriver",Jc=9515,Kc=`http://localhost:${Jc}/wd/hub`,Hw=[`--port=${Jc}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],qw=async()=>{let s=_.flags.chromedriverCdnBinariesUrl.getValue(),e=Oe(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await $i(gt(),`${$m} --detect_chromedriver_version ${e}`)},zw=async()=>{process.env.NODE_OPTIONS="",await(0,Bm.default)(`:${Jc}`,{silent:!0}),await Xt($m).start(Hw,!0)},Kw=async({chromeBinaryLocation:s})=>{await(0,jm.default)(async()=>{var n;let e=await Te(`${Kc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await We({url:`${Kc}/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 Ws(`${Kc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var rn={};H(rn,{getSessionPlayerFolder:()=>Zc,prepareChromeDriver:()=>tn,prepareCustomExtension:()=>Xc,prepareExtension:()=>Qc,preparePlayer:()=>br});async function Xc(s,e=!1){if(!s)return;if(Oe(s)){let n=es.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Jw(s)>Yc&&!e)throw new C(Gm);return await Ke(s,n),n}let t=es.resolve(s);if(!qm.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(Rc(t)>Yc&&!e)throw new C(Gm);return t}async function Jw(s){let e=(Ve(),He(ze));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Vi.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function Qc(s){Vi.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Ii(t)}));return Bt(()=>se(e,({location:t,path:r})=>Ri(t,r)),"prepareExtension",Km,e)()}async function tn(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(Vm(),Wm));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 Vr||(Vi.error(a,{...s,...Fi(),error:(0,zm.serializeError)(o)}),console.log(`
11
11
  1. If you don't have Chrome, please install it from https://www.google.com/chrome.
12
12
  2. If Chrome is installed, please verify it's binary directory:
13
13
  - installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
14
14
  - exists in your PATH environment variables.
15
15
  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").
16
- 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 Kw(){let s=Ht==="staging"?`${Ds}/Staging-LATEST_VERSION`:`${Ms}/extension/sessionPlayer_LATEST_RELEASE`;return(await Mt(s)).body.toString("utf8")}function Jw(){return`${Ds}/dev-sessionPlayer.zip`}async function Yw(s,e){if(!Oe(s)||Oe(s)&&e||$e)return s;let t=await Kw();return`${s}-${t}${Ht==="staging"?".zip":""}`}function Zc(){let s=gt();return es.resolve(s,"testim-bin")}function Xw(){let s=Zc();return es.resolve(s,"sessionPlayer.zip")}async function qm(s,e,t=!1){try{return await Ri(s,e),await it(e,Zc())}catch(r){if(t)throw r;return await qm(s,e,!0)}}async function br(s,e){Vi.info("prepare player",{location:s,canary:e});let t=Xw();return Bt(async()=>{let r=Ht==="development"?Jw():await Yw(s,e);return await qm(r,t),{}},"preparePlayer",Hm,[s,e,t])()}var Wm,Vm,es,Gm,Vi,Hm,Yc,$m,sn=v(()=>{"use strict";Wm=I(require("ms")),Vm=I(require("node:fs")),es=I(require("node:path"));de();Yt();Gm=require("serialize-error");W();$c();Y();F();Vi=P("prepare runner and testim start"),Hm=(0,Wm.default)("0.5 day"),Yc=16,$m=`The size of the custom extension is more than ${Yc}MB`});function Qw(){let s=nn.type().toLowerCase();return s==="darwin"?nn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?nn.arch()==="x64"?"win64":"win32":"linux"}async function Hi(){let s=Qw(),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(on,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]}/${on}/${n[s]}.zip`,a=Gi.join(el,n[s]),l=`${a}.zip`,c=Gi.join(a,i[s]);if(await ye(c))return c;if(!await ye(l)){let m=(0,tl.default)("Downloading Chromium").start();try{await zm.promises.mkdir(el),await Ke(o,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,tl.default)("Extracting Chromium").start();try{await it(l,el)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var zm,nn,Gi,tl,on,el,rl=v(()=>{"use strict";zm=I(require("fs")),nn=I(require("os")),Gi=I(require("path")),tl=I(require("ora"));Y();F();on="1000968",el=Gi.join(Ft,`chrome-${on}`)});async function Ym(s,e){return Tr=s,ol=e,await sl()}function Xm(s,e){Tr=e.projectId,ol=e.token,an=e.userAccessKey,ot=s.token,ln=al(ot),un=s.refreshToken,nl=s.ngrokToken,il=s.isNgrokWhitelisted,Km=e.publicIp,Jm=e.initializedFromCache}function ev(s=Tr,e=ol){return Bt(()=>(cn.info("request to get cli token from server"),We({url:`${he}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Zw*10,{projectId:s,token:e})()}async function tv(){cn.info("request to refresh JWT cli token from server");let s=await We({url:`${he}/auth/refreshToken`,body:{token:ot,refreshToken:un}});return ot=s.token,ln=al(ot),s.refreshToken&&(un=s.refreshToken),ot}async function sl(){try{let s=await ev();return cn.info("successfully get cli token from server"),ot=s.token,ln=al(ot),un=s.refreshToken,nl=s.ngrokToken,il=s.isNgrokWhitelisted,ot}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."):(cn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Tr}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function al(s){return require("jsonwebtoken").decode(s).exp*1e3}async function At(){if(!ln)return sl();let s=_.flags.accessTokenExpiryMargin.getValue();if(ln<Date.now()+4*s)try{return await tv()}catch(e){return cn.error("failed to refresh token, executing fallback",e),sl()}return ot}function qi(){return un}function wr(){return ot?{uid:require("jsonwebtoken").decode(ot).id,ngrokToken:nl,isNgrokWhitelisted:il}:{}}async function zi(){if(!an||!Tr)return;if(await cl({userAccessKey:an,projectId:Tr}))return an;let e=`user access key "${an}" is invalid for project "${Tr}"`;throw new C(e)}function Ki(){return Km}function Ji(){return Jm}var cn,ot,ln,un,nl,il,Tr,ol,an,Km,Jm,Zw,at=v(()=>{"use strict";de();Ve();Yt();Y();W();ge();ue();cn=P("testim-custom-token"),Tr=null,ol=null,Zw=5*60*1e3});function rv(s){if(s.protocol)return s.protocol;if([L.TESTIM_PRIVATE,L.TESTIM,L.BROWSERSTACK,L.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([L.TESTIM_ENTERPRISE,L.TESTIM_LAMBDATEST,L.DEVICE_FARM].includes(s.type)){let e=Qm.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function sv(s){let e=Qm.exec(s);return e==null?void 0:e[3]}function Xi(s){var S,E,A,D,j,R,x,O,B,G,z;let e=s&&sv(s.host),t=s.port,r=s.path,n=s&&rv(s),i=s.token,o=s.slotId,a=(S=s.hybrid)==null?void 0:S.tunnel,l=(E=s.external)==null?void 0:E.user,c=(A=s.external)==null?void 0:A.key,d=s.type,m=d===L.HYBRID?a&&((R=(j=(D=s.hybrid)==null?void 0:D.external)==null?void 0:j[s.hybrid.tunnel])==null?void 0:R.user):l,u=d===L.HYBRID?a&&((B=(O=(x=s.hybrid)==null?void 0:x.external)==null?void 0:O[s.hybrid.tunnel])==null?void 0:B.key):c,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(G=s.mobileTokens)==null?void 0:G.androidToken,T=(z=s.mobileTokens)==null?void 0:z.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:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:w,isSupportGrid:b}}async function iv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(l){throw Xe.error("failed to get grid",{projectId:s,companyId:e,err:l}),new Error(ht.UNKNOWN)}if(Xe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Xe.error("invalid response - get grid",{res:o}),new Error(ht.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,rf(n));let l=Xi(o.grid);return nv(t,e,l.gridId,l.slotId,r,l.isSupportGrid),l}throw o.code==="not-found"?new rt(ht.NOT_FOUND):o.code==="no-available-slot"?new zt(`Failed to run test on ${r} - concurrency limit reached`):(Xe.error("invalid code error response - get grid",{res:o}),new rt(ht.UNKNOWN))}function ef(s){return fl(s)}async function tf(s,e,t){let n=(t||await ef(s)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return Xi(n)}async function ov(s,e,t){let n=(t||await ef(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return Xi(n)}async function ll(s,e){let t=pn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete pn[s],!a){if(!r){Xe.warn("failed to find grid slot id",{projectId:e});return}Xe.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await pl(o,e,r,n,i)}catch(l){Xe.error("failed to release slot",{projectId:e,err:l})}}}async function av(s){let e=Object.values(pn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid){Xe.info("keep alive worker slots",{projectId:s,slots:e});try{await ul(s,e)}catch(t){Xe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function cv(s){Zm=global.setInterval(av,1e4,s)}async function lv(s){let e=Object.keys(pn);if(e.length){Xe.warn("not all slots released before end runner flow",{projectId:s});try{await se(e,t=>ll(Number(t),s))}catch(t){Xe.error("failed to release all slots",{err:t,projectId:s})}}}async function uv(s){await lv(s),clearInterval(Zm)}function pv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function dv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function rf(s){let t=(()=>Yi.isEmpty(s.testobjectSauce)?Yi.isEmpty(s.saucelabs)?Yi.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=pv(t,s),l=dv(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:l,key:a,gridId:re()}}async function sf(s,e){let t=s.company.companyId;return await tf(t,e.gridId,s.allGrids)}async function nf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:l}=s;if(n||o||i)return{mode:"local"};if(r)return rf(s);let c=t==null?void 0:t.companyId;if(a)return tf(c,a,e);if(l)return ov(c,l,e);if(Ks(s)||s.tunnelOnlyMode){Xe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new rt("Missing host or grid configuration")}async function of(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:l,localTmaUrl:c,useLocalChromeDriver:d,useChromeLauncher:m,company:u}=t,f=Boolean(d||m||c),h=u==null?void 0:u.companyId;return iv(o,h,r,s,t,()=>ml({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:l,gridName:a,host:i,testResultId:n}))}var Yi,Xe,pn,Qm,Zm,nv,dn,af,ts=v(()=>{"use strict";Yi=I(require("lodash"));ge();W();F();ie();Y();Xe=P("grid-service"),pn={},Qm=/(^(https?):\/{2})?(.*)/,Zm=null;nv=(s,e,t,r,n,i)=>{pn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};dn={start:cv,end:uv};af=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:i}={}}=s,{gridId:o,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!o||!a||((a===L.TESTIM_LAMBDATEST||a===L.LAMBDATEST)&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==L.HYBRID||!i||!l||!d||!m))return e;let u=await dl({companyId:i,gridId:o,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Xe.info("handling hybrid grid",{response:u,companyId:i});let f=Xi({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((g=r.disable)==null||g.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});function fn(){return Qi||"master"}function cf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Qi="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){Qi=s.branch||s;return}Qi=e?"master":void 0}var Qi,gl=v(()=>{"use strict";Y()});function mf(s){$e||(s!=null&&s.userId||(s={anonymousId:df}),pf.identify(s))}function yt(s,e){return gn("ci",s,e)}function gn(s,e,t){if($e)return;let r=s?{userId:s}:{anonymousId:df};pf.track(Object.assign(r,{event:e,properties:t}))}var uf,pf,df,rs=v(()=>{"use strict";de();uf=require("@segment/analytics-node"),pf=new uf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),df=require("crypto").randomBytes(20).toString("hex")});var ff={};H(ff,{isCi:()=>ss});var ss,Zi=v(()=>{"use strict";ss=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function hf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function yf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=hf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:gf(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);yt("test-run-ci",y)}function bf({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let w=hf({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:gf(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){yt("test-run-ci-success",w);return}yt("test-run-ci-fail",{...w,failureReason:n.failureReason})}catch(w){f.error("failed to update test end analytics",{err:w})}}function Tf(s){yt("batch-run-ci",s)}var gf,hl=v(()=>{"use strict";rs();Zi();gf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ss&&e?"ci-with-user":ss?"ci":e?"cli-with-user":s});var yn,yl,mv,bl,fv,eo,to,ro,so,no,io=v(()=>{"use strict";F();ie();yn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===me.FAILED},yl=s=>{let{status:e}=s;return e===me.ABORTED},mv=s=>{let{status:e}=s;return e===me.PASSED},bl=s=>s.runnerStatus===Ac.SKIPPED,fv=s=>s.testStatus===Je.EVALUATING,eo=(s,e)=>Object.values(s).filter(t=>{var r,n;return bl(t)&&(Ye(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,to=s=>Object.values(s).filter(e=>yn(e)&&fv(e)).length,ro=s=>Object.values(s).filter(yn),so=s=>Object.values(s).filter(mv),no=s=>Object.values(s).filter(yl)});function hv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Tl,oo,gv,ao,vf=v(()=>{"use strict";Tl=I(require("lodash"));W();io();oo=P("debug-reporter"),gv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],ao=class{constructor(e){this.options=e}onTestStarted(e,t){oo.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,l=r.failedGetBrowserAttempts;oo.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:l,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Tl.default.omit(this.options,gv),company:Tl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let l=hv(process.argv);oo.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,i){let o=so(e).length,a=Object.keys(e).length-o;oo.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var wl,Ct,bn=v(()=>{"use strict";ie();wl=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===L.DEVICE_FARM}},Ct=new wl});var Sl={};H(Sl,{Reporter:()=>yv});var Zt,Tn,vr,co,Sf,vl,yv,El=v(()=>{"use strict";Zt=I(require("chalk")),Tn=I(require("lodash"));F();ie();bn();io();vr={success:Zt.default.green,warn:Zt.default.yellow,error:Zt.default.red},{CLI_MODE:co}=Ut,Sf="device",vl=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: ${Zt.default.underline(qe(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?me.PASSED:me.FAILED,n=`(${e.testId})`,i=vr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Ci(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
17
- \r`)))}onTestPlanFinished(e,t,r,n,i){let o=ro(e),a=so(e),l=no(e),c=a.length,d=l.length,m=o.length,u="",f="";if(Ct.isTestStatusEnabled){let w=to(e);u=` FAILED-EVALUATING: ${w}`,m-=w,f=` SKIPPED: ${eo(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=vr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Ci(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=Tn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Tn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Tn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Tn.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 l=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)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===co.APPIUM?Sf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Zt.default.underline(n)} slot from ${Zt.default.underline(r)}`)}onGetSession(e,t,r){let n=r===co.APPIUM?Sf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Zt.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===co.APPIUM?"device":"browser";if(n)console.log(vr.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(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===co.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},yv=vl});var xl={};H(xl,{Reporter:()=>Ev});function bv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function Tv(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 wv(s){return`${s.visitedUrlsJson||""}`}async function vv(s,e,t,r,n,i){function o(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:bv(u),classname:n,time:Nc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(yn(u)||yl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=yn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return bl(u)&&Ye(u,i)&&Ct.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=Tv(u),h["visited-urls-json"]=wv(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:c(y),failures:d(y),timestamp:l(e)};if(Ct.isTestStatusEnabled){w.skipped=eo(y,i);let b=to(y);w.failures-=b,w["failure-evaluating"]=b}return{$:w,testcase:Object.keys(y).map(b=>o(y[b]))}}function l(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 c(u){return Object.keys(u).length}function d(u){return ro(u).length+no(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Rl.Builder().buildObject(m)}catch(u){return Sv(u)}}function Sv(s){let e=new Rl.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 Rl,Ef,Il,Ev,Al=v(()=>{"use strict";Rl=I(require("xml2js"));F();Ef=require("fs");bn();io();Il=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 vv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Ef.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)}};Ev=Il});var If={};H(If,{Reporter:()=>Iv});function ns(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 Cl,Pl,Iv,Rf=v(()=>{"use strict";W();Cl=P("team-city-reporter");Pl=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 ns(n)}onTestStarted(e,t,r,n){if(r){Cl.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){Cl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ns(t)}' details='${ns(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Cl.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='${ns(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ns(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ns(t)}']`)}},Iv=Pl});var xf={};H(xf,{Reporter:()=>Rv});var kl,Rv,Af=v(()=>{"use strict";kl=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}}))}},Rv=kl});function uo(s){let{platform:e}=process;e==="win32"?(0,lo.exec)(`start chrome ${s}`):e==="darwin"?(0,lo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,lo.exec)(`google-chrome ${s}`)}var lo,Ol=v(()=>{"use strict";lo=require("child_process")});var Cf={};H(Cf,{Reporter:()=>xv});var _l,xv,Pf=v(()=>{"use strict";F();Ol();_l=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return uo(t)}},xv=_l});var Ll,Q,Pt=v(()=>{"use strict";vf();Ll=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 ao(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(El(),Sl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Al(),xl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Rf(),If)),r.includes("console")&&Promise.resolve().then(()=>(El(),Sl)),r.includes("junit")&&Promise.resolve().then(()=>(Al(),xl)),r.includes("json")&&Promise.resolve().then(()=>(Af(),xf)),r.includes("chrome")&&Promise.resolve().then(()=>(Pf(),Cf))])).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 Ll});async function Dl(s,e,t){let r=is[s];if(!r)return;let{slotId:n}=r;if(delete is[s],!n){ct.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ct.info("release slot id",{companyId:e,slotId:n});try{await Ml(e,t,n)}catch(i){ct.error("failed to release slot",{companyId:e,err:i})}}async function Av(s,e){let t=Object.values(is).filter(Boolean);if(t.length!==0){ct.info("keep alive worker slots",{companyId:s,slots:t});try{await Fl(s,e,t)}catch(r){ct.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function Cv(s,e){kf=global.setInterval(()=>Av(s,e),1e4)}async function Pv(s,e){let t=Object.keys(is);if(t.length){ct.warn("not all slots released before end runner flow",{companyId:s});try{await se(t,r=>Dl(Number(r),s,e))}catch(r){ct.error("failed to release all slots",{err:r,companyId:s})}}}async function kv(s,e){await Pv(s,e),clearInterval(kf)}async function _f(s,e,t){let r;try{r=await Nl(s,e)}catch(n){throw ct.error("failed to get slot",{companyId:s,err:n}),new Error(ht.UNKNOWN)}if(ct.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ct.error("invalid response - get slot",{res:r}),new Error(ht.UNKNOWN);if(r.status==="success")return Of(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new rt(ht.NOT_FOUND):r.code==="no-available-slot"?new zt("Failed to run test - concurrency limit reached"):(ct.error("invalid code error response - get slot",{res:r}),new rt(ht.UNKNOWN))}async function Lf(s,e,t,r){let n=is[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Of(r,n),await Ul(s,e,n),ct.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ct,is,kf,Of,wn,os=v(()=>{"use strict";ge();W();F();ie();Y();ct=P("slot-service"),is={},kf=null,Of=(s,e)=>{is[s]=e};wn={start:Cv,end:kv}});function Nf(s,e=process){async function t(r){await le(se(Df,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Sn.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(Sn.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",()=>{Sn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Sn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Sn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function as(s){Df.push(s)}var Sn,Df,En=v(()=>{"use strict";W();F();Sn=P("process-handler"),Df=[]});var Bf={};H(Bf,{installAllLazyDependencies:()=>Dv,lazyRequire:()=>lt});async function lt(s,e={}){let t=Gc(s);if(t)return t;let r;e.silent||(r=(0,Mf.default)(`Installing ${s} before first usage...`).start());try{let n=await Lv(s);return r&&r.succeed(),n}catch(n){_v.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Ff(s),o=`${s}@${i}`,l=process.argv.includes("npx")?"":"-g ",c=`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 ${l}${o}`;throw r&&r.fail(c),n}}async function Lv(s){return cs.has(s)||(cs.set(s,Uf(s)),cs.get(s).catch(()=>{cs.delete(s)})),cs.get(s)}async function Uf(s){let e=Gc(s);if(e)return e;let t=Ff(s),r=`${s}@${t}`;return await $i(gt(),r),Xt(s)}async function Dv(){let s=Object.keys(nc);for(let e of s)await Uf(e)}function Ff(s){let e=Object.entries(nc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Mf,_v,cs,In=v(()=>{"use strict";Mf=I(require("ora"));Zr();W();F();mi();en();_v=P("lazy-require"),cs=new Map});var jf,po,$f=v(()=>{"use strict";jf=require("istanbul-lib-report"),po=class extends jf.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 Wf,Vf,Gf,Rn,bt,Hf,mo,Bl,qf,Nv,zf,Kf,Mv,Uv,Jf,Fv,Bv,jv,$v,Wv,Yf,Xf=v(()=>{"use strict";Wf=I(require("ora")),Vf=I(require("dayjs")),Gf=I(require("test-exclude")),Rn=I(require("fs")),bt=I(require("path")),Hf=I(require("istanbul-reports")),mo=I(require("istanbul-lib-report"));ge();Y();F();W();In();$f();Bl=P("test-run-status"),qf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Nv=s=>!!qf(s).search,zf=s=>s?qf(s).pathname.substring(1):"",Kf=(s,e)=>{let t=zf(e);return!new Gf.default({relativePath:!1,include:s}).shouldInstrument(t)},Mv=s=>s.substring(0,s.indexOf("?")),Uv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await lt("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)},Jf=(s,e)=>`${bt.resolve(s,zf(e))}.js`,Fv=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(Kf(r,o))return;let l=Jf(e,o);await Rn.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await Rn.promises.writeFile(l,i.sourcesContent[a])})})},Bv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Nv(e)&&(e=Mv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},jv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=mo.createContext({dir:t,coverageMap:e,watermarks:mo.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Jf(r,a);return Rn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new po({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:Bv}),Hf.create(a,l).execute(o)}),i},$v=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await lt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Kf(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},Wv=async(s,e)=>{let{mergeProcessCovs:r}=await lt("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await $l(s,"testResult",`runId=${e}`)).data.docs;return await se(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await xn(l,9e4);await se(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await jl(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},Yf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Bl.info("start js coverage process");let n=(0,Wf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=bt.resolve(s.codeCoverageReportPath||"./coverage"),o=bt.resolve(i,`.js/${(0,Vf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([lt("istanbul-lib-coverage"),Wv(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Bl.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await se(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),w=await Uv({sourceMapType:T,source:y,sourceMapDir:a});u[h]=w;let b=await $v(s,{source:y,sourceMap:w,functions:g});m.merge(b)}),await Fv(s,o,u);let f=await jv(s,m,i,o);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof C?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Bl.error(c,{err:l})}}});var Qf={};H(Qf,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Sr});var xe,Vv,Sr,ls=v(()=>{"use strict";F();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Vv=["ALL",...Object.values(xe)],Sr=class{constructor(){this.marks=Object.fromEntries(Vv.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`,Oi(r,50)],[`${t}_P95`,Oi(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var rg={};H(rg,{initServer:()=>qv,mapFilesToLocalDrive:()=>Vl});function Vl(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,fo[t.id]?{screenshot:fo[t.id]}:{})),Object.keys(go).forEach(t=>{s.assets||={},s.assets[tg[t]]=go[t]}),s.assets||={},s.assets.screenshots=Object.values(fo)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function qv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await lt("multer"),n=typeof t=="string"?t:Gv;await Wl.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=An.join(n,m.testResultId);try{await Wl.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=An.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,eg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(fo[d.stepId]=l.file.path),d.testResultId&&Hv.includes(d.subType)&&(go[d.subType]||=[],go[d.subType].push(l.file.path)),c.sendStatus(200)}),o.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new C(`Port ${s} is already in use`));default:return c(u)}}})}var Wl,Zf,An,eg,Gv,fo,go,tg,Hv,Gl=v(()=>{"use strict";Wl=I(require("fs")),Zf=I(require("os")),An=I(require("path")),eg=I(require("express"));Y();In();Gv=An.join(Zf.tmpdir(),"testim/rca/"),fo={},go={},tg={"test-log":"consoleLogs","har-file":"networkLogs"},Hv=Object.keys(tg)});var er,Hl,ho,sg=v(()=>{"use strict";er=I(require("lodash"));F();W();Hl=P("override-test-data-builder"),ho=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return er.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)&&!er.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Hl.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(er.isObject(e.overrideAllTestsData)&&!er.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Hl.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}Hl.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 er.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}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 yo(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 Er,Qe,zv,Kv,Jv,Yv,bo,ng=v(()=>{"use strict";Er=I(require("lodash"));F();ie();ts();os();ge();Y();W();Pt();En();Xf();ls();Gl();de();ue();sg();bn();Qe=P("test-run-status"),zv=fr(),Kv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Jv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Yv=tt();bo=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 Sr;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=zs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:hi||t.parallel||1,browser:i,gitBranch:zv,gitCommit:Kv,gitRepoUrl:Jv,runnerVersion:Yv,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w}=a,b={originalTestResultId:t,previousTestResultId:r,config:Er.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w},Kl({projectId:n,runId:i,testId:c,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 c;let{project:n,remoteRunId:i,projectData:o}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await wo(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let l=Er.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,Ir(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await yo(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:l,success:c}=t;if(a===Je.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Je.EVALUATING} status`);return}if(c){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?me.PASSED:me.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Je.QUARANTINE}`)}monitorMemoryUsage(e){let t=Mc();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&&Vl(o,Qe),o.resultUrl=qe(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 l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await yo(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 Ir(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}=kc;return e&&(n=i),Hr(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 l=e.browser?Ys(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=qr(_,n)&&Js(a.nativeApp)&&!e.appId,d=Jt(e)&&(Hr(a.nativeApp,n)||c),m=Ye(a,e)||d,u={testId:a.testId,testOptimization:a.testOptimization,status:m?me.SKIPPED:me.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Je.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,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:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await wn.end(r,t),e==="mongo"&&await dn.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:l,company:{companyId:c}={},slotService:d}=o;as(()=>Promise.all([this.endKeepAlive(d,t,c),To("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,..._.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await yo(o.beforeSuite,m),f=new ho(u,Er.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=Er.cloneDeep(this.testRunStatus);await se(Object.keys(b),async A=>{var O;let D=b[A],j=(O=D.config)==null?void 0:O.testData,R=D.testId,x=await wo(t,R,A,j,l.defaults);x&&(delete D.config.testData,D.config.testDataUrl=x)});let S=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),E=zl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:S,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){Er.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=Fc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===me.PASSED&&n++,m===me.SKIPPED&&i++,m===me.FAILED&&u===Je.EVALUATING&&o++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await yo(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Qe.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Yf(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await To("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Qe.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await ql(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 Jl(s,e){var o;let t=s.canary?"-master.zip":".zip",r=`${e?Id:Ms}/extension/testim-headless${t}`,n=_.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(o=s.company)==null?void 0:o.companyId,projectId:s.project,runnerEnvironment:Ht});return n||(Xv.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),n="https://testimstatic.blob.core.windows.net/extension/testim-headless.zip"),!(s.ext||s.extensionPath)&&n&&(r=n,s.testimHeadlessExtensionDownloadUrl=n),{chrome:r,"edge-chromium":r}}function ig(s){let{chrome:e}=Jl(s,!1);return e}function vo(s){let e=Ht==="staging"?`${Ds}/staging-sessionPlayer`:`${Ms}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Xv,Cn=v(()=>{"use strict";de();ue();W();Xv=P("runOptionsUtils")});function ag(s,e){if(e){if(!sS.has(e)){Pn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var cg,lg,jt,ug,pg,dg,So,mg,Pn,Qv,Zv,kn,eS,tS,rS,ne,sS,Eo=v(()=>{"use strict";cg=I(require("ms")),lg=I(require("p-retry")),jt=I(require("node:os")),ug=I(require("portfinder")),pg=I(require("node:child_process"));F();Ve();ge();dg=I(require("node:fs")),So=I(require("node:fs/promises")),mg=require("node:path");Y();W();Cn();ie();ue();F();Pn=P("lambdatestService"),Qv="https://downloads.lambdatest.com/tunnel/v3",Zv={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"},kn=`${jt.tmpdir()}/LT`,eS=`${kn}/LT`,tS=(0,cg.default)("15m"),rS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===L.TESTIM_LAMBDATEST||e.type===L.LAMBDATEST||e.type===L.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=Yl(),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?tS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(eS))return;let t=Zv[jt.platform()+jt.arch()];if(!t)throw new Error(`tunnel on ${jt.platform()+jt.arch()} platform is not supported.`);let r=`${kn}.zip`;await Ke(`${Qv}/${t}`,r),await it(r,kn)}static async chmodLtTunnel(e){if(!(jt.platform()==="win32"||!await ye(e))){try{await So.access(e,dg.constants.X_OK);return}catch{}try{await So.chmod(e,"777")}catch(r){throw Pn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ce(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await ug.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;ne.tunnelName=re();let c=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(_.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(_.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Dc(u)])}if(_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--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)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new C("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await ne.delay(3e3),await ne.chmodLtTunnel((0,mg.join)(kn,"LT")),ne.tunnel=pg.spawn("./LT",c,{cwd:kn});let d="",m="";ne.tunnel.stdout.on("data",u=>{d+=u.toString()}),ne.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,lg.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Pn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),Pn.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,l){var T,w;if(!this.isActive)return{};let c=ne.lambdatestConfig.CAPABILITIES[t]||{},d={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:ag(n,a==null?void 0:a.os)||ag(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??rS,version:t==="safari"&&((w=o==null?void 0:o.lt)==null?void 0:w.safari_version)||c.version};if(l!==q.APPIUM&&l!==q.SELENIUM&&!f){let b=Jl({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&Oe(h)&&(m=[...m,h]),m.length||Pn.warn("No extension was loaded in LambdaTestService",{extUrls:b,extensionPath:h})}return _.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&Oe(g)&&(m=[...m,g]),{build:r,name:`${n} - ${i}`,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:_.flags.LTNetworkCapabilities.isEnabled(),ntlm:_.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},sS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"])});function iS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function vg(s){return yg.readFileSync(s,{encoding:"base64"})}function Sg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&Oe(s))&&s){let r=vg(s);ps.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Zl(r)} current extension count: ${e.length}`),e.push(r)}}function Eg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;ps.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=Io.basename(i));let l=Io.join(process.cwd(),a),c=vg(l);ps.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${Zl(c)} current extension count: ${e.length}`),e.push(c)}function oS(s,e,t,r,n,i,o,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...wg];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Xl.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Xl.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(Ql(n)){let T=_.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=_.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}Ql(n)&&l==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Xl.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Cc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),Sg(r,c,o),a===q.EXTENSION&&Eg(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return ne.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function cS(s,e,t){let r={"pdfjs.disabled":!0};return _.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":gg.join(","),"browser.helperApps.neverAsk.openFile":gg.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 us(s){return`${s.width}x${s.height}`}function fS(s){let{platform:e}=s;if(!e)return us(hg);let t=e.split(" ")[1];return e.startsWith("Windows")&&mS.has(t)?us(uS):e==="Linux"?us(lS):e.startsWith("macOS")?us(pS):us(e==="OS X El Capitan"||e==="OS X Yosemite"?dS:hg)}function gS(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=fS(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,Tg.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,ut.merge(i,n,r)}return ut.merge(n,r)}return{}}function hS(s,e,t){return ut.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function yS(s){return s.perfecto?s.perfecto:{}}function bS(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 TS(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=tc(i,o)),a}function Ro(s){var w,b,S,E;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let A=[],D=[...wg],j={};return t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>D.push(`--${R}`)),t.chromeBinaryLocation&&(j.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&Eg(t,A,D,null,c),Sg(o,A,c),{logLevel:fg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:A,...j},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=TS(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.protocol||"http",logLevel:fg,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ut.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Ql(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);ut.merge(h.desiredCapabilities,gS(t,r,n),hS(t,r,n),yS(t),bS(t,y,g),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((w=i.host)!=null&&w.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&_.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=aS(h,t,n,o,i,T,c,d);break;case"firefox":h=cS(h,t,c);break;case"safari":case"safari technology preview":h=iS(h,y);break;default:break}ut.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let A={"hub.lambdatest.com":"lambdatest",[_.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=O=>O[i.provider]||O[h.host]||O[A[h.host]],j=O=>{var B,G;return D(O)||O[(B=h.desiredCapabilities)==null?void 0:B.browserName]||O[(G=h.desiredCapabilities)==null?void 0:G.version]||O||{}},R=JSON.parse(_.flags.addCustomCapabilities.getValue()||"{}"),x=j(j(R));Object.keys(x).length&&(ps.info(`Adding custom capabilities: ${JSON.stringify(x)}`),Object.assign(h.desiredCapabilities,x))}catch(A){ps.error("Failed to load custom capabilities",{error:A,customCapabilities:_.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(nS(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let A=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),j=(S=D==null?void 0:D.capabilities)==null?void 0:S.alwaysMatch,R=O=>O.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(O=>{var B,G;j!=null&&j[O]&&(j[O].extensions=(G=(B=A==null?void 0:A[O])==null?void 0:B.extensions)==null?void 0:G.map(R))}),j!=null&&j.loadExtension&&(j.loadExtension=(E=A==null?void 0:A.loadExtension)==null?void 0:E.map(R));let x=require("node:util");console.log(x.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var yg,Io,bg,ut,Tg,ps,fg,Xl,wg,Zl,Ql,nS,aS,gg,hg,lS,uS,pS,dS,mS,eu=v(()=>{"use strict";yg=I(require("node:fs")),Io=I(require("node:path")),bg=I(require("node:crypto")),ut=I(require("lodash"));F();de();W();ue();ie();Eo();Tg=require("lodash"),ps=P("testim-desired-capabilities-builder"),fg=gi?"debug":"silent",Xl={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},wg=["--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"],Zl=(...s)=>bg.createHash("sha256").update(s.join("")).digest("hex"),Ql=s=>s.type===L.DEVICE_FARM||s.type===L.HYBRID&&s.provider==="devicefarm",nS=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=_.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ps.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};aS=ut.memoize(oS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(ut.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Zl(o,a,l,r,c,i)}),gg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];hg={width:1920,height:1080},lS={width:1920,height:1200},uS={width:2560,height:1600},pS={width:2360,height:1770},dS={width:2048,height:1536},mS=new Set(["7","8","8.1","10","11"])});function Ue(s){var e,t,r,n,i,o,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((i=s.seleniumStack)==null?void 0:i.message)==="The arguments passed to a command are either invalid or malformed."||((o=s.message)==null?void 0:o.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function Rg(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 tu=v(()=>{"use strict"});function ru(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 l(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:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(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 ru(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||l(s))}var xg=v(()=>{"use strict"});var Ag,Cg,$t,wS,vS,xo,Pg=v(()=>{"use strict";Ag=I(require("promise-queue")),Cg=I(require("webdriverio"));de();je();F();W();jr();xg();tu();ls();$t=P("WebDriverApi"),wS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},vS={implicit:0,pageLoad:1,script:2},xo=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 $t.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),ic!==void 0&&(e=ic);let t=1/0;this.queue=new Ag.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,l,c,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(c=(l=e.capabilities.alwaysMatch)==null?void 0:l["goog:chromeOptions"])==null?void 0:c.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{$t.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await Cg.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,xe.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 l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){$t.info("grid status is not supported by the grid",{testResultId:e});return}$t.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),$t.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){$t.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(xe.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,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(_e(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.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(ru,{ELEMENT:e,[Gt]: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(Rg(e,this.isSafari(),$t))})}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[vS[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(_e(e)),await this.elementIdValue(_e(e),t)}async getViewportSize(e){let t=await this.execute(wS);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(_e(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 l;return(l=this.client)==null?void 0:l.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){$t.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()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}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 $t.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 tr={};H(tr,{getSessionPlayer:()=>Z,options:()=>nu});var Ao,nu,su,Z,we=v(()=>{"use strict";Ao=require("path");W();nu={playerPath:void 0},Z=()=>{if(su)return su;let s=(je(),He(Be));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(sn(),He(rn)),t=e(),r=nu.playerPath?(0,Ao.resolve)(nu.playerPath,"src/background/sessionPlayerInit.ts"):(0,Ao.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),su=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(Fd),n}});var kg={};H(kg,{doubleClick:()=>SS});var SS,Og=v(()=>{"use strict";SS=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,S){return S>w&&S<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}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var On={};H(On,{dispatchFocus:()=>ES});function ES(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 _n=v(()=>{"use strict"});var Mg={};H(Mg,{WebDriver:()=>Ar});async function AS(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 RS(r):void 0}catch(r){Fe.info("Error getting cdpAddress",r);return}}var ds,Dg,Ng,Fe,rr,IS,_g,RS,Rr,xS,Lg,xr,Ar,Ln=v(()=>{"use strict";ds=I(require("lodash"));F();je();eu();Dg=I(require("p-retry")),Ng=I(require("ua-parser-js"));jr();W();tu();Pg();Y();ue();ls();Fe=P("webdriver"),[rr,IS]=[0,2],{extractElementId:_g,getCdpAddressForHost:RS}=J,Rr=()=>(we(),He(tr)).getSessionPlayer().codeSnippets,xS=()=>(we(),He(tr)).getSessionPlayer().locatorBuilderUtils,Lg=()=>(we(),He(tr)).getSessionPlayer().utils,xr=()=>(we(),He(tr)).getSessionPlayer().positionUtils;Ar=class extends xo{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}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)}async init(t){var b,S,E,A,D,j,R,x;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((E=(S=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:S.premiumFeatures)==null?void 0:E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Ro({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,w=u?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let O=await this.initClient(y,i,d);M("after initResult before getCdpAddress in init"),this.cdpUrl=await AS(O),M("after getCdpAddress in webdriver.js init"),Fe.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ce(T),_.flags.dontFocusOnInit.isEnabled()||await w(),M("after focus and delay in webdriver.js init")}catch(O){let B=JSON.stringify(ds.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Fe.error("failed to init webdriver",{err:O,capabilitiesAsString:B});let G=((D=(A=n==null?void 0:n.company)==null?void 0:A.activePlan)==null?void 0:D.plan)==="free";throw(j=O.stack)!=null&&j.includes("at startWebDriverSession")&&((R=O.message)!=null&&R.startsWith("Failed to create session"))&&((x=O.message)!=null&&x.includes("Timeout awaiting 'request'"))&&G?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(O.message)?new Wr(O.message):/capabilit(y|ies)/.test(O.message)?new wi(O.message):/403 Forbidden/.test(O.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(O.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${O.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ds.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,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[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}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Fe.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Fe.warn("failed to click on alert",{err:l}));return}if(Fe.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Fe.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=_g(r.value);return await this.switchToFrame({ELEMENT:n,[Gt]: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 vi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||_.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
16
+ 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 Yw(){let s=Ht==="staging"?`${Ds}/Staging-LATEST_VERSION`:`${Ms}/extension/sessionPlayer_LATEST_RELEASE`;return(await Mt(s)).body.toString("utf8")}function Xw(){return`${Ds}/dev-sessionPlayer.zip`}async function Qw(s,e){if(!Oe(s)||Oe(s)&&e||$e)return s;let t=await Yw();return`${s}-${t}${Ht==="staging"?".zip":""}`}function Zc(){let s=gt();return es.resolve(s,"testim-bin")}function Zw(){let s=Zc();return es.resolve(s,"sessionPlayer.zip")}async function Jm(s,e,t=!1){try{return await Ri(s,e),await it(e,Zc())}catch(r){if(t)throw r;return await Jm(s,e,!0)}}async function br(s,e){Vi.info("prepare player",{location:s,canary:e});let t=Zw();return Bt(async()=>{let r=Ht==="development"?Xw():await Qw(s,e);return await Jm(r,t),{}},"preparePlayer",Km,[s,e,t])()}var Hm,qm,es,zm,Vi,Km,Yc,Gm,sn=v(()=>{"use strict";Hm=I(require("ms")),qm=I(require("node:fs")),es=I(require("node:path"));de();Yt();zm=require("serialize-error");W();$c();Y();F();Vi=P("prepare runner and testim start"),Km=(0,Hm.default)("0.5 day"),Yc=16,Gm=`The size of the custom extension is more than ${Yc}MB`});function ev(){let s=nn.type().toLowerCase();return s==="darwin"?nn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?nn.arch()==="x64"?"win64":"win32":"linux"}async function Hi(){let s=ev(),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(on,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]}/${on}/${n[s]}.zip`,a=Gi.join(el,n[s]),l=`${a}.zip`,c=Gi.join(a,i[s]);if(await ye(c))return c;if(!await ye(l)){let m=(0,tl.default)("Downloading Chromium").start();try{await Ym.promises.mkdir(el),await Ke(o,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,tl.default)("Extracting Chromium").start();try{await it(l,el)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Ym,nn,Gi,tl,on,el,rl=v(()=>{"use strict";Ym=I(require("fs")),nn=I(require("os")),Gi=I(require("path")),tl=I(require("ora"));Y();F();on="1000968",el=Gi.join(Ft,`chrome-${on}`)});async function Zm(s,e){return Tr=s,ol=e,await sl()}function ef(s,e){Tr=e.projectId,ol=e.token,an=e.userAccessKey,ot=s.token,ln=al(ot),un=s.refreshToken,nl=s.ngrokToken,il=s.isNgrokWhitelisted,Xm=e.publicIp,Qm=e.initializedFromCache}function rv(s=Tr,e=ol){return Bt(()=>(cn.info("request to get cli token from server"),We({url:`${he}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",tv*10,{projectId:s,token:e})()}async function sv(){cn.info("request to refresh JWT cli token from server");let s=await We({url:`${he}/auth/refreshToken`,body:{token:ot,refreshToken:un}});return ot=s.token,ln=al(ot),s.refreshToken&&(un=s.refreshToken),ot}async function sl(){try{let s=await rv();return cn.info("successfully get cli token from server"),ot=s.token,ln=al(ot),un=s.refreshToken,nl=s.ngrokToken,il=s.isNgrokWhitelisted,ot}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."):(cn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Tr}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function al(s){return require("jsonwebtoken").decode(s).exp*1e3}async function At(){if(!ln)return sl();let s=_.flags.accessTokenExpiryMargin.getValue();if(ln<Date.now()+4*s)try{return await sv()}catch(e){return cn.error("failed to refresh token, executing fallback",e),sl()}return ot}function qi(){return un}function wr(){return ot?{uid:require("jsonwebtoken").decode(ot).id,ngrokToken:nl,isNgrokWhitelisted:il}:{}}async function zi(){if(!an||!Tr)return;if(await cl({userAccessKey:an,projectId:Tr}))return an;let e=`user access key "${an}" is invalid for project "${Tr}"`;throw new C(e)}function Ki(){return Xm}function Ji(){return Qm}var cn,ot,ln,un,nl,il,Tr,ol,an,Xm,Qm,tv,at=v(()=>{"use strict";de();Ve();Yt();Y();W();ge();ue();cn=P("testim-custom-token"),Tr=null,ol=null,tv=5*60*1e3});function nv(s){if(s.protocol)return s.protocol;if([L.TESTIM_PRIVATE,L.TESTIM,L.BROWSERSTACK,L.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([L.TESTIM_ENTERPRISE,L.TESTIM_LAMBDATEST,L.DEVICE_FARM].includes(s.type)){let e=tf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function iv(s){let e=tf.exec(s);return e==null?void 0:e[3]}function Xi(s){var S,E,A,D,j,R,x,O,B,G,z;let e=s&&iv(s.host),t=s.port,r=s.path,n=s&&nv(s),i=s.token,o=s.slotId,a=(S=s.hybrid)==null?void 0:S.tunnel,l=(E=s.external)==null?void 0:E.user,c=(A=s.external)==null?void 0:A.key,d=s.type,m=d===L.HYBRID?a&&((R=(j=(D=s.hybrid)==null?void 0:D.external)==null?void 0:j[s.hybrid.tunnel])==null?void 0:R.user):l,u=d===L.HYBRID?a&&((B=(O=(x=s.hybrid)==null?void 0:x.external)==null?void 0:O[s.hybrid.tunnel])==null?void 0:B.key):c,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(G=s.mobileTokens)==null?void 0:G.androidToken,T=(z=s.mobileTokens)==null?void 0:z.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:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:w,isSupportGrid:b}}async function av(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(l){throw Xe.error("failed to get grid",{projectId:s,companyId:e,err:l}),new Error(ht.UNKNOWN)}if(Xe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Xe.error("invalid response - get grid",{res:o}),new Error(ht.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,of(n));let l=Xi(o.grid);return ov(t,e,l.gridId,l.slotId,r,l.isSupportGrid),l}throw o.code==="not-found"?new rt(ht.NOT_FOUND):o.code==="no-available-slot"?new zt(`Failed to run test on ${r} - concurrency limit reached`):(Xe.error("invalid code error response - get grid",{res:o}),new rt(ht.UNKNOWN))}function sf(s){return fl(s)}async function nf(s,e,t){let n=(t||await sf(s)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return Xi(n)}async function cv(s,e,t){let n=(t||await sf(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return Xi(n)}async function ll(s,e){let t=pn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete pn[s],!a){if(!r){Xe.warn("failed to find grid slot id",{projectId:e});return}Xe.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await pl(o,e,r,n,i)}catch(l){Xe.error("failed to release slot",{projectId:e,err:l})}}}async function lv(s){let e=Object.values(pn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid){Xe.info("keep alive worker slots",{projectId:s,slots:e});try{await ul(s,e)}catch(t){Xe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function uv(s){rf=global.setInterval(lv,1e4,s)}async function pv(s){let e=Object.keys(pn);if(e.length){Xe.warn("not all slots released before end runner flow",{projectId:s});try{await se(e,t=>ll(Number(t),s))}catch(t){Xe.error("failed to release all slots",{err:t,projectId:s})}}}async function dv(s){await pv(s),clearInterval(rf)}function mv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function fv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function of(s){let t=(()=>Yi.isEmpty(s.testobjectSauce)?Yi.isEmpty(s.saucelabs)?Yi.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=mv(t,s),l=fv(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:l,key:a,gridId:re()}}async function af(s,e){let t=s.company.companyId;return await nf(t,e.gridId,s.allGrids)}async function cf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:l}=s;if(n||o||i)return{mode:"local"};if(r)return of(s);let c=t==null?void 0:t.companyId;if(a)return nf(c,a,e);if(l)return cv(c,l,e);if(Ks(s)||s.tunnelOnlyMode){Xe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new rt("Missing host or grid configuration")}async function lf(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:l,localTmaUrl:c,useLocalChromeDriver:d,useChromeLauncher:m,company:u}=t,f=Boolean(d||m||c),h=u==null?void 0:u.companyId;return av(o,h,r,s,t,()=>ml({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:l,gridName:a,host:i,testResultId:n}))}var Yi,Xe,pn,tf,rf,ov,dn,uf,ts=v(()=>{"use strict";Yi=I(require("lodash"));ge();W();F();ie();Y();Xe=P("grid-service"),pn={},tf=/(^(https?):\/{2})?(.*)/,rf=null;ov=(s,e,t,r,n,i)=>{pn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};dn={start:uv,end:dv};uf=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:i}={}}=s,{gridId:o,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!o||!a||((a===L.TESTIM_LAMBDATEST||a===L.LAMBDATEST)&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==L.HYBRID||!i||!l||!d||!m))return e;let u=await dl({companyId:i,gridId:o,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Xe.info("handling hybrid grid",{response:u,companyId:i});let f=Xi({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((g=r.disable)==null||g.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});function fn(){return Qi||"master"}function pf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Qi="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){Qi=s.branch||s;return}Qi=e?"master":void 0}var Qi,gl=v(()=>{"use strict";Y()});function hf(s){$e||(s!=null&&s.userId||(s={anonymousId:gf}),ff.identify(s))}function yt(s,e){return gn("ci",s,e)}function gn(s,e,t){if($e)return;let r=s?{userId:s}:{anonymousId:gf};ff.track(Object.assign(r,{event:e,properties:t}))}var mf,ff,gf,rs=v(()=>{"use strict";de();mf=require("@segment/analytics-node"),ff=new mf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),gf=require("crypto").randomBytes(20).toString("hex")});var yf={};H(yf,{isCi:()=>ss});var ss,Zi=v(()=>{"use strict";ss=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Tf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function wf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Tf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:bf(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);yt("test-run-ci",y)}function vf({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let w=Tf({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:bf(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){yt("test-run-ci-success",w);return}yt("test-run-ci-fail",{...w,failureReason:n.failureReason})}catch(w){f.error("failed to update test end analytics",{err:w})}}function Sf(s){yt("batch-run-ci",s)}var bf,hl=v(()=>{"use strict";rs();Zi();bf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ss&&e?"ci-with-user":ss?"ci":e?"cli-with-user":s});var yn,yl,gv,bl,hv,eo,to,ro,so,no,io=v(()=>{"use strict";F();ie();yn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===me.FAILED},yl=s=>{let{status:e}=s;return e===me.ABORTED},gv=s=>{let{status:e}=s;return e===me.PASSED},bl=s=>s.runnerStatus===Ac.SKIPPED,hv=s=>s.testStatus===Je.EVALUATING,eo=(s,e)=>Object.values(s).filter(t=>{var r,n;return bl(t)&&(Ye(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,to=s=>Object.values(s).filter(e=>yn(e)&&hv(e)).length,ro=s=>Object.values(s).filter(yn),so=s=>Object.values(s).filter(gv),no=s=>Object.values(s).filter(yl)});function bv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Tl,oo,yv,ao,If=v(()=>{"use strict";Tl=I(require("lodash"));W();io();oo=P("debug-reporter"),yv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],ao=class{constructor(e){this.options=e}onTestStarted(e,t){oo.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,l=r.failedGetBrowserAttempts;oo.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:l,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Tl.default.omit(this.options,yv),company:Tl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let l=bv(process.argv);oo.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,i){let o=so(e).length,a=Object.keys(e).length-o;oo.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var wl,Ct,bn=v(()=>{"use strict";ie();wl=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===L.DEVICE_FARM}},Ct=new wl});var Sl={};H(Sl,{Reporter:()=>Tv});var Zt,Tn,vr,co,Rf,vl,Tv,El=v(()=>{"use strict";Zt=I(require("chalk")),Tn=I(require("lodash"));F();ie();bn();io();vr={success:Zt.default.green,warn:Zt.default.yellow,error:Zt.default.red},{CLI_MODE:co}=Ut,Rf="device",vl=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: ${Zt.default.underline(qe(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?me.PASSED:me.FAILED,n=`(${e.testId})`,i=vr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Ci(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
17
+ \r`)))}onTestPlanFinished(e,t,r,n,i){let o=ro(e),a=so(e),l=no(e),c=a.length,d=l.length,m=o.length,u="",f="";if(Ct.isTestStatusEnabled){let w=to(e);u=` FAILED-EVALUATING: ${w}`,m-=w,f=` SKIPPED: ${eo(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=vr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Ci(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=Tn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Tn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Tn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Tn.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 l=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)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===co.APPIUM?Rf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Zt.default.underline(n)} slot from ${Zt.default.underline(r)}`)}onGetSession(e,t,r){let n=r===co.APPIUM?Rf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Zt.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===co.APPIUM?"device":"browser";if(n)console.log(vr.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(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===co.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},Tv=vl});var xl={};H(xl,{Reporter:()=>Rv});function wv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function vv(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 Sv(s){return`${s.visitedUrlsJson||""}`}async function Ev(s,e,t,r,n,i){function o(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:wv(u),classname:n,time:Nc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(yn(u)||yl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=yn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return bl(u)&&Ye(u,i)&&Ct.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=vv(u),h["visited-urls-json"]=Sv(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:c(y),failures:d(y),timestamp:l(e)};if(Ct.isTestStatusEnabled){w.skipped=eo(y,i);let b=to(y);w.failures-=b,w["failure-evaluating"]=b}return{$:w,testcase:Object.keys(y).map(b=>o(y[b]))}}function l(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 c(u){return Object.keys(u).length}function d(u){return ro(u).length+no(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Rl.Builder().buildObject(m)}catch(u){return Iv(u)}}function Iv(s){let e=new Rl.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 Rl,xf,Il,Rv,Al=v(()=>{"use strict";Rl=I(require("xml2js"));F();xf=require("fs");bn();io();Il=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 Ev(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await xf.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)}};Rv=Il});var Af={};H(Af,{Reporter:()=>xv});function ns(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 Cl,Pl,xv,Cf=v(()=>{"use strict";W();Cl=P("team-city-reporter");Pl=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 ns(n)}onTestStarted(e,t,r,n){if(r){Cl.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){Cl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ns(t)}' details='${ns(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Cl.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='${ns(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ns(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ns(t)}']`)}},xv=Pl});var Pf={};H(Pf,{Reporter:()=>Av});var kl,Av,kf=v(()=>{"use strict";kl=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}}))}},Av=kl});function uo(s){let{platform:e}=process;e==="win32"?(0,lo.exec)(`start chrome ${s}`):e==="darwin"?(0,lo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,lo.exec)(`google-chrome ${s}`)}var lo,Ol=v(()=>{"use strict";lo=require("child_process")});var Of={};H(Of,{Reporter:()=>Cv});var _l,Cv,_f=v(()=>{"use strict";F();Ol();_l=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return uo(t)}},Cv=_l});var Ll,Q,Pt=v(()=>{"use strict";If();Ll=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 ao(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(El(),Sl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Al(),xl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Cf(),Af)),r.includes("console")&&Promise.resolve().then(()=>(El(),Sl)),r.includes("junit")&&Promise.resolve().then(()=>(Al(),xl)),r.includes("json")&&Promise.resolve().then(()=>(kf(),Pf)),r.includes("chrome")&&Promise.resolve().then(()=>(_f(),Of))])).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 Ll});async function Dl(s,e,t){let r=is[s];if(!r)return;let{slotId:n}=r;if(delete is[s],!n){ct.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ct.info("release slot id",{companyId:e,slotId:n});try{await Ml(e,t,n)}catch(i){ct.error("failed to release slot",{companyId:e,err:i})}}async function Pv(s,e){let t=Object.values(is).filter(Boolean);if(t.length!==0){ct.info("keep alive worker slots",{companyId:s,slots:t});try{await Fl(s,e,t)}catch(r){ct.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function kv(s,e){Lf=global.setInterval(()=>Pv(s,e),1e4)}async function Ov(s,e){let t=Object.keys(is);if(t.length){ct.warn("not all slots released before end runner flow",{companyId:s});try{await se(t,r=>Dl(Number(r),s,e))}catch(r){ct.error("failed to release all slots",{err:r,companyId:s})}}}async function _v(s,e){await Ov(s,e),clearInterval(Lf)}async function Nf(s,e,t){let r;try{r=await Nl(s,e)}catch(n){throw ct.error("failed to get slot",{companyId:s,err:n}),new Error(ht.UNKNOWN)}if(ct.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ct.error("invalid response - get slot",{res:r}),new Error(ht.UNKNOWN);if(r.status==="success")return Df(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new rt(ht.NOT_FOUND):r.code==="no-available-slot"?new zt("Failed to run test - concurrency limit reached"):(ct.error("invalid code error response - get slot",{res:r}),new rt(ht.UNKNOWN))}async function Mf(s,e,t,r){let n=is[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Df(r,n),await Ul(s,e,n),ct.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ct,is,Lf,Df,wn,os=v(()=>{"use strict";ge();W();F();ie();Y();ct=P("slot-service"),is={},Lf=null,Df=(s,e)=>{is[s]=e};wn={start:kv,end:_v}});function Ff(s,e=process){async function t(r){await le(se(Uf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Sn.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(Sn.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",()=>{Sn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Sn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Sn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function as(s){Uf.push(s)}var Sn,Uf,En=v(()=>{"use strict";W();F();Sn=P("process-handler"),Uf=[]});var Wf={};H(Wf,{installAllLazyDependencies:()=>Mv,lazyRequire:()=>lt});async function lt(s,e={}){let t=Gc(s);if(t)return t;let r;e.silent||(r=(0,Bf.default)(`Installing ${s} before first usage...`).start());try{let n=await Nv(s);return r&&r.succeed(),n}catch(n){Dv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=$f(s),o=`${s}@${i}`,l=process.argv.includes("npx")?"":"-g ",c=`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 ${l}${o}`;throw r&&r.fail(c),n}}async function Nv(s){return cs.has(s)||(cs.set(s,jf(s)),cs.get(s).catch(()=>{cs.delete(s)})),cs.get(s)}async function jf(s){let e=Gc(s);if(e)return e;let t=$f(s),r=`${s}@${t}`;return await $i(gt(),r),Xt(s)}async function Mv(){let s=Object.keys(nc);for(let e of s)await jf(e)}function $f(s){let e=Object.entries(nc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Bf,Dv,cs,In=v(()=>{"use strict";Bf=I(require("ora"));Zr();W();F();mi();en();Dv=P("lazy-require"),cs=new Map});var Vf,po,Gf=v(()=>{"use strict";Vf=require("istanbul-lib-report"),po=class extends Vf.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 Hf,qf,zf,Rn,bt,Kf,mo,Bl,Jf,Uv,Yf,Xf,Fv,Bv,Qf,jv,$v,Wv,Vv,Gv,Zf,eg=v(()=>{"use strict";Hf=I(require("ora")),qf=I(require("dayjs")),zf=I(require("test-exclude")),Rn=I(require("fs")),bt=I(require("path")),Kf=I(require("istanbul-reports")),mo=I(require("istanbul-lib-report"));ge();Y();F();W();In();Gf();Bl=P("test-run-status"),Jf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Uv=s=>!!Jf(s).search,Yf=s=>s?Jf(s).pathname.substring(1):"",Xf=(s,e)=>{let t=Yf(e);return!new zf.default({relativePath:!1,include:s}).shouldInstrument(t)},Fv=s=>s.substring(0,s.indexOf("?")),Bv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await lt("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)},Qf=(s,e)=>`${bt.resolve(s,Yf(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(Xf(r,o))return;let l=Qf(e,o);await Rn.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await Rn.promises.writeFile(l,i.sourcesContent[a])})})},$v={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Uv(e)&&(e=Fv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Wv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=mo.createContext({dir:t,coverageMap:e,watermarks:mo.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Qf(r,a);return Rn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new po({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:$v}),Kf.create(a,l).execute(o)}),i},Vv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await lt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Xf(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},Gv=async(s,e)=>{let{mergeProcessCovs:r}=await lt("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await $l(s,"testResult",`runId=${e}`)).data.docs;return await se(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await xn(l,9e4);await se(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await jl(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},Zf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Bl.info("start js coverage process");let n=(0,Hf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=bt.resolve(s.codeCoverageReportPath||"./coverage"),o=bt.resolve(i,`.js/${(0,qf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([lt("istanbul-lib-coverage"),Gv(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Bl.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await se(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),w=await Bv({sourceMapType:T,source:y,sourceMapDir:a});u[h]=w;let b=await Vv(s,{source:y,sourceMap:w,functions:g});m.merge(b)}),await jv(s,o,u);let f=await Wv(s,m,i,o);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof C?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Bl.error(c,{err:l})}}});var tg={};H(tg,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Sr});var xe,Hv,Sr,ls=v(()=>{"use strict";F();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Hv=["ALL",...Object.values(xe)],Sr=class{constructor(){this.marks=Object.fromEntries(Hv.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`,Oi(r,50)],[`${t}_P95`,Oi(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var ig={};H(ig,{initServer:()=>Kv,mapFilesToLocalDrive:()=>Vl});function Vl(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,fo[t.id]?{screenshot:fo[t.id]}:{})),Object.keys(go).forEach(t=>{s.assets||={},s.assets[ng[t]]=go[t]}),s.assets||={},s.assets.screenshots=Object.values(fo)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function Kv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await lt("multer"),n=typeof t=="string"?t:qv;await Wl.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=An.join(n,m.testResultId);try{await Wl.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=An.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,sg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(fo[d.stepId]=l.file.path),d.testResultId&&zv.includes(d.subType)&&(go[d.subType]||=[],go[d.subType].push(l.file.path)),c.sendStatus(200)}),o.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new C(`Port ${s} is already in use`));default:return c(u)}}})}var Wl,rg,An,sg,qv,fo,go,ng,zv,Gl=v(()=>{"use strict";Wl=I(require("fs")),rg=I(require("os")),An=I(require("path")),sg=I(require("express"));Y();In();qv=An.join(rg.tmpdir(),"testim/rca/"),fo={},go={},ng={"test-log":"consoleLogs","har-file":"networkLogs"},zv=Object.keys(ng)});var er,Hl,ho,og=v(()=>{"use strict";er=I(require("lodash"));F();W();Hl=P("override-test-data-builder"),ho=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return er.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)&&!er.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Hl.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(er.isObject(e.overrideAllTestsData)&&!er.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Hl.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}Hl.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 er.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}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 yo(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 Er,Qe,Jv,Yv,Xv,Qv,bo,ag=v(()=>{"use strict";Er=I(require("lodash"));F();ie();ts();os();ge();Y();W();Pt();En();eg();ls();Gl();de();ue();og();bn();Qe=P("test-run-status"),Jv=fr(),Yv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Xv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Qv=tt();bo=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 Sr;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=zs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:hi||t.parallel||1,browser:i,gitBranch:Jv,gitCommit:Yv,gitRepoUrl:Xv,runnerVersion:Qv,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w}=a,b={originalTestResultId:t,previousTestResultId:r,config:Er.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w},Kl({projectId:n,runId:i,testId:c,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 c;let{project:n,remoteRunId:i,projectData:o}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await wo(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let l=Er.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,Ir(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await yo(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:l,success:c}=t;if(a===Je.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Je.EVALUATING} status`);return}if(c){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?me.PASSED:me.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Je.QUARANTINE}`)}monitorMemoryUsage(e){let t=Mc();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&&Vl(o,Qe),o.resultUrl=qe(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 l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await yo(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 Ir(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}=kc;return e&&(n=i),Hr(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 l=e.browser?Ys(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=qr(_,n)&&Js(a.nativeApp)&&!e.appId,d=Jt(e)&&(Hr(a.nativeApp,n)||c),m=Ye(a,e)||d,u={testId:a.testId,testOptimization:a.testOptimization,status:m?me.SKIPPED:me.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Je.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,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:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await wn.end(r,t),e==="mongo"&&await dn.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:l,company:{companyId:c}={},slotService:d}=o;as(()=>Promise.all([this.endKeepAlive(d,t,c),To("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,..._.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await yo(o.beforeSuite,m),f=new ho(u,Er.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=Er.cloneDeep(this.testRunStatus);await se(Object.keys(b),async A=>{var O;let D=b[A],j=(O=D.config)==null?void 0:O.testData,R=D.testId,x=await wo(t,R,A,j,l.defaults);x&&(delete D.config.testData,D.config.testDataUrl=x)});let S=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),E=zl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:S,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){Er.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=Fc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===me.PASSED&&n++,m===me.SKIPPED&&i++,m===me.FAILED&&u===Je.EVALUATING&&o++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await yo(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Qe.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Zf(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await To("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Qe.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await ql(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 Jl(s,e){var o;let t=s.canary?"-master.zip":".zip",r=`${e?Rd:Ms}/extension/testim-headless${t}`,n=_.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(o=s.company)==null?void 0:o.companyId,projectId:s.project,runnerEnvironment:Ht});return n||(Zv.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),n="https://testimstatic.blob.core.windows.net/extension/testim-headless.zip"),!(s.ext||s.extensionPath)&&n&&(r=n,s.testimHeadlessExtensionDownloadUrl=n),{chrome:r,"edge-chromium":r}}function cg(s){let{chrome:e}=Jl(s,!1);return e}function vo(s){let e=Ht==="staging"?`${Ds}/staging-sessionPlayer`:`${Ms}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Zv,Cn=v(()=>{"use strict";de();ue();W();Zv=P("runOptionsUtils")});function ug(s,e){if(e){if(!iS.has(e)){Pn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var pg,dg,jt,mg,fg,gg,So,hg,Pn,eS,tS,kn,rS,sS,nS,ne,iS,Eo=v(()=>{"use strict";pg=I(require("ms")),dg=I(require("p-retry")),jt=I(require("node:os")),mg=I(require("portfinder")),fg=I(require("node:child_process"));F();Ve();ge();gg=I(require("node:fs")),So=I(require("node:fs/promises")),hg=require("node:path");Y();W();Cn();ie();ue();F();Pn=P("lambdatestService"),eS="https://downloads.lambdatest.com/tunnel/v3",tS={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"},kn=`${jt.tmpdir()}/LT`,rS=`${kn}/LT`,sS=(0,pg.default)("15m"),nS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===L.TESTIM_LAMBDATEST||e.type===L.LAMBDATEST||e.type===L.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=Yl(),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?sS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(rS))return;let t=tS[jt.platform()+jt.arch()];if(!t)throw new Error(`tunnel on ${jt.platform()+jt.arch()} platform is not supported.`);let r=`${kn}.zip`;await Ke(`${eS}/${t}`,r),await it(r,kn)}static async chmodLtTunnel(e){if(!(jt.platform()==="win32"||!await ye(e))){try{await So.access(e,gg.constants.X_OK);return}catch{}try{await So.chmod(e,"777")}catch(r){throw Pn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ce(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await mg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;ne.tunnelName=re();let c=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(_.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(_.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Dc(u)])}if(_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--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)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new C("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await ne.delay(3e3),await ne.chmodLtTunnel((0,hg.join)(kn,"LT")),ne.tunnel=fg.spawn("./LT",c,{cwd:kn});let d="",m="";ne.tunnel.stdout.on("data",u=>{d+=u.toString()}),ne.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,dg.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Pn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),Pn.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,l){var T,w;if(!this.isActive)return{};let c=ne.lambdatestConfig.CAPABILITIES[t]||{},d={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:ug(n,a==null?void 0:a.os)||ug(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??nS,version:t==="safari"&&((w=o==null?void 0:o.lt)==null?void 0:w.safari_version)||c.version};if(l!==q.APPIUM&&l!==q.SELENIUM&&!f){let b=Jl({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&Oe(h)&&(m=[...m,h]),m.length||Pn.warn("No extension was loaded in LambdaTestService",{extUrls:b,extensionPath:h})}return _.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&Oe(g)&&(m=[...m,g]),{build:r,name:`${n} - ${i}`,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:_.flags.LTNetworkCapabilities.isEnabled(),ntlm:_.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},iS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"])});function aS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Ig(s){return wg.readFileSync(s,{encoding:"base64"})}function Rg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&Oe(s))&&s){let r=Ig(s);ps.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Zl(r)} current extension count: ${e.length}`),e.push(r)}}function xg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;ps.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=Io.basename(i));let l=Io.join(process.cwd(),a),c=Ig(l);ps.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${Zl(c)} current extension count: ${e.length}`),e.push(c)}function cS(s,e,t,r,n,i,o,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...Eg];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Xl.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Xl.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(Ql(n)){let T=_.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=_.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}Ql(n)&&l==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Xl.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Cc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),Rg(r,c,o),a===q.EXTENSION&&xg(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return ne.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function uS(s,e,t){let r={"pdfjs.disabled":!0};return _.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":bg.join(","),"browser.helperApps.neverAsk.openFile":bg.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 us(s){return`${s.width}x${s.height}`}function hS(s){let{platform:e}=s;if(!e)return us(Tg);let t=e.split(" ")[1];return e.startsWith("Windows")&&gS.has(t)?us(dS):e==="Linux"?us(pS):e.startsWith("macOS")?us(mS):us(e==="OS X El Capitan"||e==="OS X Yosemite"?fS:Tg)}function yS(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=hS(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,Sg.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,ut.merge(i,n,r)}return ut.merge(n,r)}return{}}function bS(s,e,t){return ut.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function TS(s){return s.perfecto?s.perfecto:{}}function wS(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 vS(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=tc(i,o)),a}function Ro(s){var w,b,S,E;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let A=[],D=[...Eg],j={};return t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>D.push(`--${R}`)),t.chromeBinaryLocation&&(j.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&xg(t,A,D,null,c),Rg(o,A,c),{logLevel:yg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:A,...j},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=vS(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.protocol||"http",logLevel:yg,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ut.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Ql(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);ut.merge(h.desiredCapabilities,yS(t,r,n),bS(t,r,n),TS(t),wS(t,y,g),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((w=i.host)!=null&&w.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&_.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=lS(h,t,n,o,i,T,c,d);break;case"firefox":h=uS(h,t,c);break;case"safari":case"safari technology preview":h=aS(h,y);break;default:break}ut.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let A={"hub.lambdatest.com":"lambdatest",[_.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=O=>O[i.provider]||O[h.host]||O[A[h.host]],j=O=>{var B,G;return D(O)||O[(B=h.desiredCapabilities)==null?void 0:B.browserName]||O[(G=h.desiredCapabilities)==null?void 0:G.version]||O||{}},R=JSON.parse(_.flags.addCustomCapabilities.getValue()||"{}"),x=j(j(R));Object.keys(x).length&&(ps.info(`Adding custom capabilities: ${JSON.stringify(x)}`),Object.assign(h.desiredCapabilities,x))}catch(A){ps.error("Failed to load custom capabilities",{error:A,customCapabilities:_.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(oS(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let A=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),j=(S=D==null?void 0:D.capabilities)==null?void 0:S.alwaysMatch,R=O=>O.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(O=>{var B,G;j!=null&&j[O]&&(j[O].extensions=(G=(B=A==null?void 0:A[O])==null?void 0:B.extensions)==null?void 0:G.map(R))}),j!=null&&j.loadExtension&&(j.loadExtension=(E=A==null?void 0:A.loadExtension)==null?void 0:E.map(R));let x=require("node:util");console.log(x.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var wg,Io,vg,ut,Sg,ps,yg,Xl,Eg,Zl,Ql,oS,lS,bg,Tg,pS,dS,mS,fS,gS,eu=v(()=>{"use strict";wg=I(require("node:fs")),Io=I(require("node:path")),vg=I(require("node:crypto")),ut=I(require("lodash"));F();de();W();ue();ie();Eo();Sg=require("lodash"),ps=P("testim-desired-capabilities-builder"),yg=gi?"debug":"silent",Xl={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Eg=["--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"],Zl=(...s)=>vg.createHash("sha256").update(s.join("")).digest("hex"),Ql=s=>s.type===L.DEVICE_FARM||s.type===L.HYBRID&&s.provider==="devicefarm",oS=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=_.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ps.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};lS=ut.memoize(cS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(ut.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Zl(o,a,l,r,c,i)}),bg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Tg={width:1920,height:1080},pS={width:1920,height:1200},dS={width:2560,height:1600},mS={width:2360,height:1770},fS={width:2048,height:1536},gS=new Set(["7","8","8.1","10","11"])});function Ue(s){var e,t,r,n,i,o,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((i=s.seleniumStack)==null?void 0:i.message)==="The arguments passed to a command are either invalid or malformed."||((o=s.message)==null?void 0:o.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function Cg(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 tu=v(()=>{"use strict"});function ru(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 l(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:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(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 ru(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||l(s))}var Pg=v(()=>{"use strict"});var kg,Og,$t,SS,ES,xo,_g=v(()=>{"use strict";kg=I(require("promise-queue")),Og=I(require("webdriverio"));de();je();F();W();jr();Pg();tu();ls();$t=P("WebDriverApi"),SS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},ES={implicit:0,pageLoad:1,script:2},xo=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 $t.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),ic!==void 0&&(e=ic);let t=1/0;this.queue=new kg.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,l,c,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(c=(l=e.capabilities.alwaysMatch)==null?void 0:l["goog:chromeOptions"])==null?void 0:c.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{$t.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await Og.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,xe.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 l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){$t.info("grid status is not supported by the grid",{testResultId:e});return}$t.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),$t.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){$t.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(xe.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,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(_e(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.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(ru,{ELEMENT:e,[Gt]: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(Cg(e,this.isSafari(),$t))})}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[ES[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(_e(e)),await this.elementIdValue(_e(e),t)}async getViewportSize(e){let t=await this.execute(SS);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(_e(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 l;return(l=this.client)==null?void 0:l.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){$t.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()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}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 $t.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 tr={};H(tr,{getSessionPlayer:()=>Z,options:()=>nu});var Ao,nu,su,Z,we=v(()=>{"use strict";Ao=require("path");W();nu={playerPath:void 0},Z=()=>{if(su)return su;let s=(je(),He(Be));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(sn(),He(rn)),t=e(),r=nu.playerPath?(0,Ao.resolve)(nu.playerPath,"src/background/sessionPlayerInit.ts"):(0,Ao.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),su=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(Bd),n}});var Lg={};H(Lg,{doubleClick:()=>IS});var IS,Dg=v(()=>{"use strict";IS=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,S){return S>w&&S<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}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var On={};H(On,{dispatchFocus:()=>RS});function RS(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 _n=v(()=>{"use strict"});var Bg={};H(Bg,{WebDriver:()=>Ar});async function PS(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 AS(r):void 0}catch(r){Fe.info("Error getting cdpAddress",r);return}}var ds,Ug,Fg,Fe,rr,xS,Ng,AS,Rr,CS,Mg,xr,Ar,Ln=v(()=>{"use strict";ds=I(require("lodash"));F();je();eu();Ug=I(require("p-retry")),Fg=I(require("ua-parser-js"));jr();W();tu();_g();Y();ue();ls();Fe=P("webdriver"),[rr,xS]=[0,2],{extractElementId:Ng,getCdpAddressForHost:AS}=J,Rr=()=>(we(),He(tr)).getSessionPlayer().codeSnippets,CS=()=>(we(),He(tr)).getSessionPlayer().locatorBuilderUtils,Mg=()=>(we(),He(tr)).getSessionPlayer().utils,xr=()=>(we(),He(tr)).getSessionPlayer().positionUtils;Ar=class extends xo{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}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)}async init(t){var b,S,E,A,D,j,R,x;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((E=(S=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:S.premiumFeatures)==null?void 0:E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Ro({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,w=u?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let O=await this.initClient(y,i,d);M("after initResult before getCdpAddress in init"),this.cdpUrl=await PS(O),M("after getCdpAddress in webdriver.js init"),Fe.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ce(T),_.flags.dontFocusOnInit.isEnabled()||await w(),M("after focus and delay in webdriver.js init")}catch(O){let B=JSON.stringify(ds.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Fe.error("failed to init webdriver",{err:O,capabilitiesAsString:B});let G=((D=(A=n==null?void 0:n.company)==null?void 0:A.activePlan)==null?void 0:D.plan)==="free";throw(j=O.stack)!=null&&j.includes("at startWebDriverSession")&&((R=O.message)!=null&&R.startsWith("Failed to create session"))&&((x=O.message)!=null&&x.includes("Timeout awaiting 'request'"))&&G?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(O.message)?new Wr(O.message):/capabilit(y|ies)/.test(O.message)?new wi(O.message):/403 Forbidden/.test(O.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(O.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${O.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ds.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,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[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}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Fe.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Fe.warn("failed to click on alert",{err:l}));return}if(Fe.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Fe.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Ng(r.value);return await this.switchToFrame({ELEMENT:n,[Gt]: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 vi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||_.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
18
18
  var fn = ${Rr().getLocatedElementCode};
19
19
  return fn.apply(null, arguments);
20
20
  `,t)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.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 l=getLocatedElement(a);if(!l)throw new Error("could not find dynamic parent");l.setAttribute(i,o)}await this.executeJS(`
21
21
  var getLocatedElement = ${Rr().getLocatedElementCode};
22
22
  var setDynamicParentAttribute = ${n.toString()};
23
23
  return setDynamicParentAttribute.apply(null, arguments)
24
- `,{attributeName:xS().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,l=i.getBoundingClientRect();return{top:Math.round(l.top+o),left:Math.round(l.left+a)}}return this.executeJS(`
24
+ `,{attributeName:CS().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,l=i.getBoundingClientRect();return{top:Math.round(l.top+o),left:Math.round(l.left+a)}}return this.executeJS(`
25
25
  const getLocatedElement = ${Rr().getLocatedElementCode};
26
26
  const getLocation = ${r.toString()};
27
27
  return getLocation.apply(null, arguments)
@@ -33,22 +33,22 @@ Testim had missing write access to ${r||e}
33
33
  const getLocatedElement = ${Rr().getLocatedElementCode};
34
34
  const extractText = ${r.toString()};
35
35
  return extractText.apply(null, arguments)
36
- `,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var i,o;let r=Rr().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(xe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,xe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,xe.GET_HTML);let l=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(l,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),l}}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,Dg.default)(async()=>{let{value:c}=await this.windowHandleSize(),{value:d}=await this.execute(o),m=c.width-d.screenWidth,u=c.height-d.screenHeight;await this.windowHandleSize({width:t.width+m,height:t.height+u});let{value:f}=await this.execute(o);if(f.screenWidth!==t.width||f.screenHeight!==t.height)throw new i},{retries:5-1,factor:1,minTimeout:0}).catch(c=>{if(!(c instanceof i))throw c});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 Fe.error("failed to get browser version",{err:n}),0}}async getBrowserAndOS(){function t(a){let l=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(l[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(l[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";l=l[2]?[l[1],l[2]]:[a.appName,a.appVersion,"-?"];let c=a.match(/version\/(\d+)/i);return c!==null&&l.splice(1,1,c[1]),l[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,Ng.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=xr().calculateElementMiddlePoint(n),a=i.x,l=i.y;return!Lg().isWithinBounds(n.left,n.left+n.width,o.x+a)||!Lg().isWithinBounds(n.top,n.top+n.height,o.y+l)?(Fe.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,l,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(l){Fe.error("tried to use element origin but failed because of visibility, trying absolute",l);let{x:c,y:d}=this.computeAbsoluteMovement(t),m=this.getMoveActions(c,d);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:m.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,rr,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(Og(),kg)),Promise.resolve().then(()=>(_n(),On))]);return this.executeCodeAsync(`
36
+ `,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var i,o;let r=Rr().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(xe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,xe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,xe.GET_HTML);let l=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(l,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),l}}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,Ug.default)(async()=>{let{value:c}=await this.windowHandleSize(),{value:d}=await this.execute(o),m=c.width-d.screenWidth,u=c.height-d.screenHeight;await this.windowHandleSize({width:t.width+m,height:t.height+u});let{value:f}=await this.execute(o);if(f.screenWidth!==t.width||f.screenHeight!==t.height)throw new i},{retries:5-1,factor:1,minTimeout:0}).catch(c=>{if(!(c instanceof i))throw c});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 Fe.error("failed to get browser version",{err:n}),0}}async getBrowserAndOS(){function t(a){let l=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(l[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(l[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";l=l[2]?[l[1],l[2]]:[a.appName,a.appVersion,"-?"];let c=a.match(/version\/(\d+)/i);return c!==null&&l.splice(1,1,c[1]),l[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,Fg.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=xr().calculateElementMiddlePoint(n),a=i.x,l=i.y;return!Mg().isWithinBounds(n.left,n.left+n.width,o.x+a)||!Mg().isWithinBounds(n.top,n.top+n.height,o.y+l)?(Fe.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,l,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(l){Fe.error("tried to use element origin but failed because of visibility, trying absolute",l);let{x:c,y:d}=this.computeAbsoluteMovement(t),m=this.getMoveActions(c,d);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:m.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,rr,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(Dg(),Lg)),Promise.resolve().then(()=>(_n(),On))]);return this.executeCodeAsync(`
37
37
  var getLocatedElement = ${Rr().getLocatedElementCode};
38
38
  var dispatchFocus = ${n.toString()};
39
39
  var doubleClick = ${r.toString()};
40
40
  var eventData = arguments[0];
41
41
  var done = arguments[1];
42
42
  return doubleClick.call(null, eventData, done);
43
- `,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,rr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,IS,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 Fe.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:l}=n.value;return{x:r.left+i+a/2,y:r.top+o+l/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){Fe.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),l=this.getClickActions(["pointerDown"],rr),c=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],rr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(l).concat(c).concat(d)}])}async drag(t,r,n,i,o){let{width:a,height:l}=r,c=n-a/2+1,d=i-l/2,m=this.getDragCoordinates(o),{xDiff:u,yDiff:f}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,c,d);try{return await this.dragWithMoveTo(t,u,f,c,d)}catch(h){if(Ue(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,c,d);throw h}}getMoveRelativeSequence(t,r,n,i){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},l={x:n,y:i},c=10,d=Math.round(o(a,l)/c),m=Array.from({length:d},()=>({x:Math.round((l.x-a.x)/d),y:Math.round((l.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,i){return this.getMoveRelativeSequence(t,r,n,i).reduce((a,l)=>{let c=a.at(-1);return a.concat({x:Math.round(c.x+l.x),y:Math.round(c.y+l.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:i,fromX:o,fromY:a,toRect:l,toX:c,toY:d}=n,m=xr().calculateElementMiddlePoint(i),u=xr().calculateElementMiddlePoint(l),f=this.getMoveRelativeSequence(m.x+o,m.y+a,u.x+c,u.y+d);await this.moveTo(t,Math.floor(o),Math.floor(a)),await this.buttonDown();for(let h of f)await this.moveTo(null,h.x,h.y);return await this.moveTo(r,Math.round(c),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:l}=t,c=xr().calculateElementMiddlePoint(r),d=xr().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),T=this.getClickActions(["pointerDown"],rr),w=ds.flatMap(g,A=>this.getMoveActions(A.x,A.y)),b=this.getMoveActions(f,h),S=this.getClickActions(["pointerUp"],rr),E=y.concat(T).concat(w).concat(b).concat(S);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:l}=t,c=xr().calculateElementMiddlePoint(r),d=xr().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],rr);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],rr);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(_g(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){Fe.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(){Fe.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Fe.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 iu,ou,Dn,au=v(()=>{"use strict";W();ue();ge();iu=P("lab-features-service"),ou=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(iu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await cu(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){iu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=_.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(l=>l.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 iu.error(t,{featureFlagName:e.name}),new Error(t)}},Dn=new ou});function CS(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function PS(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 kS(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function OS(s,e,t,r,n={},i=void 0,o=void 0){let a=Object.keys(n).map(h=>`
44
- var res = requireOrImportMethod('${CS(n[h])}');
43
+ `,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,rr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,xS,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 Fe.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:l}=n.value;return{x:r.left+i+a/2,y:r.top+o+l/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){Fe.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),l=this.getClickActions(["pointerDown"],rr),c=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],rr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(l).concat(c).concat(d)}])}async drag(t,r,n,i,o){let{width:a,height:l}=r,c=n-a/2+1,d=i-l/2,m=this.getDragCoordinates(o),{xDiff:u,yDiff:f}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,c,d);try{return await this.dragWithMoveTo(t,u,f,c,d)}catch(h){if(Ue(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,c,d);throw h}}getMoveRelativeSequence(t,r,n,i){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},l={x:n,y:i},c=10,d=Math.round(o(a,l)/c),m=Array.from({length:d},()=>({x:Math.round((l.x-a.x)/d),y:Math.round((l.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,i){return this.getMoveRelativeSequence(t,r,n,i).reduce((a,l)=>{let c=a.at(-1);return a.concat({x:Math.round(c.x+l.x),y:Math.round(c.y+l.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:i,fromX:o,fromY:a,toRect:l,toX:c,toY:d}=n,m=xr().calculateElementMiddlePoint(i),u=xr().calculateElementMiddlePoint(l),f=this.getMoveRelativeSequence(m.x+o,m.y+a,u.x+c,u.y+d);await this.moveTo(t,Math.floor(o),Math.floor(a)),await this.buttonDown();for(let h of f)await this.moveTo(null,h.x,h.y);return await this.moveTo(r,Math.round(c),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:l}=t,c=xr().calculateElementMiddlePoint(r),d=xr().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),T=this.getClickActions(["pointerDown"],rr),w=ds.flatMap(g,A=>this.getMoveActions(A.x,A.y)),b=this.getMoveActions(f,h),S=this.getClickActions(["pointerUp"],rr),E=y.concat(T).concat(w).concat(b).concat(S);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:l}=t,c=xr().calculateElementMiddlePoint(r),d=xr().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],rr);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],rr);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(Ng(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){Fe.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(){Fe.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Fe.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 iu,ou,Dn,au=v(()=>{"use strict";W();ue();ge();iu=P("lab-features-service"),ou=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(iu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await cu(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){iu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=_.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(l=>l.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 iu.error(t,{featureFlagName:e.name}),new Error(t)}},Dn=new ou});function kS(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function OS(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 LS(s,e,t,r,n={},i=void 0,o=void 0){let a=Object.keys(n).map(h=>`
44
+ var res = requireOrImportMethod('${kS(n[h])}');
45
45
  if (res.sync) {
46
46
  var ${h} = res.lib;
47
47
  } else {
48
48
  var ${h} = await res.lib;
49
49
  }
50
50
  `).join(""),l=o?`
51
- ${Bg.default.toString()}
51
+ ${Wg.default.toString()}
52
52
  var fileBuffer = dataUriToBuffer('${o}');
53
53
  `:"var fileBuffer = null;",c=`
54
54
  const getMessage = arguments => {
@@ -104,7 +104,7 @@ Testim had missing write access to ${r||e}
104
104
  });
105
105
  `,d=`
106
106
  function injectCode(params, args, incomingParams, context, code) {
107
- const constructWithArguments = ${kS.toString()}
107
+ const constructWithArguments = ${_S.toString()}
108
108
 
109
109
  const resolve = result => {
110
110
  parentPort.postMessage({
@@ -170,7 +170,7 @@ Testim had missing write access to ${r||e}
170
170
  // A hack to fix an issue with stringified functions which use require. when compiling to JS, calls to require change to __require.
171
171
  const __require = require;
172
172
  const { parentPort } = require('worker_threads');
173
- const requireOrImportMethod = ${PS.toString()}
173
+ const requireOrImportMethod = ${OS.toString()}
174
174
 
175
175
  // requireCode will set async to be true if needed.
176
176
  ${a}
@@ -208,73 +208,73 @@ Testim had missing write access to ${r||e}
208
208
  injectCode(params, args, incomingParams, context, code);
209
209
  });
210
210
  })();
211
- `,u=[],f=new jg.Worker(m,{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};pt.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"?pt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):pt.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",()=>{pt.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 oe))throw h;return pt.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 _S(s){try{await Ug.promises.rm(s,{recursive:!0,force:!0})}catch(e){pt.warn("failed to remove install npm packages folder",{err:e})}}function $g(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function fs(s,e,t,r,n,i){let o=$g(n,e,s,t),{data:a}=await LS(o,r,i);return a}async function gs(s,e,t,r,n,i,o,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||_.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=_m(y.testimPackageLocalLocation);return[y.paramName,ms.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=$g(o,n,e,i);if(c){let y=await xn(c);y&&(l=y)}Buffer.isBuffer(l)&&(pt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let f="data:,";return l==="data:"&&(pt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=f),{...await OS(u,t,r,s,m,a,l),nodeVersion:process.version}}async function LS(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Wg(),o=_.flags.reuseCliPkgInstallFolder.isEnabled()?n:ms.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Hc(o,r,a,t),pt.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=km(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ms.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw pt.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await le(l(),t)}catch(c){throw c instanceof oe&&pt.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Wg(){return ms.join(Fg.tmpdir(),"/testim_local_packages")}function DS(){let s=Wg();return _S(s)}var Ug,Fg,ms,Bg,jg,pt,hs=v(()=>{"use strict";Ug=I(require("fs")),Fg=I(require("os")),ms=I(require("path"));F();Zr();Bg=I(require("data-uri-to-buffer")),jg=require("worker_threads");Y();W();ge();Zr();ue();pt=P("cli-service");DS().catch(s=>pt.warn("failed to clean local package folder",{err:s}))});var sr={};H(sr,{run:()=>MS});function NS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=_.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var MS,Vg=v(()=>{"use strict";hs();Y();ue();MS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await gs(r,n,i,o,a,l,c,d,m,u);return f&&NS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof oe?new Error("Timeout while running action"):f}}});var lu={};H(lu,{run:()=>US});var US,Gg=v(()=>{"use strict";hs();Y();US=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await fs(t,r,n,o,i,a),success:!0}}catch(l){if(l instanceof Rt)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof oe)return{success:!1,code:"timeout"};throw l}}});async function qg(s,e,t,r){try{return await uu(s,e,t,r)}catch{Co.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function BS(s,e,t,r,n){return Co.info("finished to run remote step",{stepId:t,sessionId:n}),await qg(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Hg(s,e,t,r,n){return Co.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await qg(s,e,t,{status:"completed",success:!1,failureReason:r})}async function zg(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(),l=t.id;Co.info("start play remote step",{stepType:o,stepId:l,sessionId:a});let c=FS[o];if(!c)return await Hg(n,r,l,`Failed to find step type ${o}`,a);try{let d=await c.run(e,t,i);return await BS(n,r,l,d,a)}catch(d){return await Hg(n,r,l,d.message,a)}}var Co,FS,Kg=v(()=>{"use strict";Vg();ge();Gg();W();Co=P("step-playback"),FS={"cli-validation-code-step":sr,"cli-wait-for-code-step":sr,"cli-action-code-step":sr,"cli-api-code-step":sr,"cli-condition-step":sr,"cli-download-code-step":sr,"node-package":lu}});var Yg={};H(Yg,{preloadTests:()=>Mn});async function Mn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await Bt(async()=>{let t=await se(s.testId,r=>Un({...e,testId:r}),{concurrency:2});return Jg.keyBy(t,"testData.id")},"loadTests",$S,[e,s.testId])()}var Jg,$S,Po=v(()=>{"use strict";Jg=I(require("lodash"));Yt();ge();F();$S=1e3*60*60*10});var pu,Xg,Cr,WS,du,Tt,ko=v(()=>{"use strict";F();at();pu=I(require("ws")),Xg=require("events");W();de();Cr=P("socket-service"),WS=5e3,du=class extends Xg.EventEmitter{constructor(){super(...arguments);this.clientId=re();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Cr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),WS)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Cr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(hd);return At().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new pu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return Cr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{Cr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===pu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Cr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Cr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Cr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(l){n(l)&&i(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=o.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=re(),l={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",c=>c.id===a,o),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}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})}},Tt=new du});var Zg,mu,VS,GS,HS,Qg,Oo,ys,fu=v(()=>{"use strict";Zg=I(require("p-retry")),mu=I(require("socket.io-client"));de();F();W();VS=50,GS=10,HS=5e3,Qg=10*1e3,Oo=P("base socket service"),ys=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Oo.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{}Oo.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===GS&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=VS)throw new Error(`Can't connect to Testim Servers.
212
- 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",()=>{Oo.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:Qg,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=mu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Qg,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=mu.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,Zg.default)(()=>le(n(),HS),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Oo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var eh={};H(eh,{remoteStepServiceSocketIO:()=>qS});var gu,qS,th=v(()=>{"use strict";fu();gu=class extends ys{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))}},qS=new gu});var rh={};H(rh,{remoteStepService:()=>bs});var hu,Fn,yu,bs,_o=v(()=>{"use strict";ko();ie();ue();({REMOTE_STEP_SAVED:hu}=xt),yu=class{async init(e){_.flags.useNewWSCLI.isEnabled()||(Fn=(await Promise.resolve().then(()=>(th(),eh))).remoteStepServiceSocketIO,Fn.init(e))}joinToRemoteStep(e){return _.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:remoteStep`,{resultId:e},[hu]):Fn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(_.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:remoteStep`,[hu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Fn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return _.flags.useNewWSCLI.isEnabled()?(Tt.removeFilter(`${e}:remoteStep`,[hu]),Promise.resolve()):Fn.unlistenToRemoteStep(e)}},bs=new yu});var bu,Pr,sh=v(()=>{"use strict";fu();bu=class extends ys{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}},Pr=new bu});var ih={};H(ih,{testResultService:()=>kt});var nh,Tu,kt,Lo=v(()=>{"use strict";nh=require("events");ko();ie();ue();sh();Tu=class extends nh.EventEmitter{init(e){if(_.flags.useNewWSCLI.isEnabled()){Tt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return _.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(_.flags.useNewWSCLI.isEnabled()){Tt.removeFilter(`${e}:testResult`,[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(_.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:testResult`,[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!_.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},kt=new Tu});var ah,ch,lh,Se,zS,uh,oh,KS,Do,ph=v(()=>{"use strict";ah=I(require("lodash"));F();de();je();rs();at();ge();Kg();ch=I(require("p-retry")),lh=require("node:url");W();Po();ls();ie();_o();Lo();ge();Se=P("test-run-handler"),zS=3,uh=20*1e3,oh=s=>JSON.stringify(s).length<uh,KS="Test couldn't be started",Do=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 Sr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;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=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?Ys(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,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 Js(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Hr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?xi.FROM_DEVICE:xi.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 Un({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await At(),refreshToken:qi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Sd,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 zi()};if(this._options.disableMockNetwork&&yt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=oh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,l=this.testId;o?(Object.assign(t,{runData:i}),Se.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):Se.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${uh} 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 Mn(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 Se.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get 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&&oh(e))return;let r=async()=>{try{return await Su(this._options.project,this._testId,this._testResultId,e)}catch(o){return Se.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),vu(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===KS||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){M("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=o||{};M("before Runtime.evaluate"),await(0,ch.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return M("after Runtime.evaluate"),c.value}catch(o){throw Se.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 lh.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)){Se.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)&&(Se.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:l,branch:c,_options:{project:d}}=this;try{let m=await kr(a,l,d,c);n(m),r||setTimeout(o,3e3)}catch(m){Se.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else kt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await kr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Se.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Se.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Me.TEST_START_TIMEOUT_MSG)}catch(i){throw Se.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Me.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await kt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Se.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||kt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Se.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=ah.debounce(async()=>{try{await kt.joinToTestResult(this._testResultId,this.testId)}catch(o){Se.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await kr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Se.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"?(Se.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 Se.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)kt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await wu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Se.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Se.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&kt.off("socket-connected",e)}}listenToRemoteStep(e){bs.listenToRemoteStep(this.testResultId,t=>{zg(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:zS;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 No,dh=v(()=>{"use strict";ph();No=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Do(e,t,l,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function fh(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Ru({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 Eu(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 Iu(s,e){let t=s.mode===q.EXTENSION?Or:Bn,r=mh.difference(zs(s,e),t);if(r.length>0)throw yt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var mh,Or,Bn,Mo=v(()=>{"use strict";mh=I(require("lodash"));F();rs();ge();Y();ie();Or=["edge-chromium","chrome"],Bn=[...Or,"firefox","safari","safari technology preview"]});var JS,YS,XS,jn,xu=v(()=>{"use strict";ts();os();W();JS=P("worker-utils"),YS=async(s,e,t)=>{e&&await ll(s,t)},XS=async(s,e,t)=>{await Dl(s,e,t)},jn=async(s,e,t,r,n,i)=>{JS.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await YS(s,e,t),n==="redis"&&await XS(s,r,t)}}});function tE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Fo,yh,Bo,Pu,bh,wt,gh,hh,Au,$n,QS,Cu,ZS,nr,eE,Uo,rE,Ot,Wn=v(()=>{"use strict";Fo=I(require("ms")),yh=I(require("lodash")),Bo=I(require("p-retry")),Pu=I(require("dayjs")),bh=I(require("dayjs/plugin/duration"));F();je();ts();os();ge();W();xu();Pt();Eo();ue();_o();Lo();at();Ve();ie();Y();Pu.default.extend(bh.default);wt=P("base-worker"),{GET_BROWSER_TIMEOUT_MSG:gh,TEST_START_TIMEOUT_MSG:hh,TEST_COMPLETE_TIMEOUT_MSG:Au}=Me,{SETUP_TIMEOUT:$n,NETWORK_ERROR:QS,GRID_ERROR:Cu,BROWSER_CLOSED:ZS,SELENIUM_ERROR:nr,UNKNOWN_ERROR:eE,MOBILE_SESSION_ERROR:Uo}=qs;rE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,i,o,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;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 of(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 Bs(!0)}async getBrowserOnce(e,t,r,n){throw new Bs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.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:me.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=qr(_,(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:me.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=_.flags.increaseTDCRequestTimeout.isEnabled(),r=e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN,n=mr(_.flags.appiumConnectionRequestTimeout.getValue(),(0,Fo.default)("2m")),i=mr(_.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===L.BROWSERSTACK||t&&r?o+(0,Fo.default)("10m"):o+(0,Fo.default)("1m")}getSessionTimeout(){if(Jt(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,Bo.default)(async()=>{let n=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Me.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,Bo.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(_f(o,a,this.id),this.options.getBrowserTimeout,Me.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 zt?wt.info("could not get grid slot due to concurrency issue",r):wt.error("error getting grid slot",{error:e,...r}),await ce(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let l=this.options.getBrowserRetries-o;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,Bo.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await af(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c,M("before getBrowserOnce");let f=await le(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Me.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw wt.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,++c),m.onDone(),!(u instanceof It)&&this.options.mode!==q.APPIUM&&await ce(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(o){throw await jn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[It,Wr].some(a=>o instanceof a)?o:o instanceof rt?new pr(o,Cu):new pr(o,nr)}return n}async runTest(e,t,r){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Jt(this.options)&&this.handleMobileTest(e);if(o)return o;M("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await At(),await this.runTestOnce(e,c)}finally{await jn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var O,B;if(Ye(g,this.options)||qr(_,(O=this.options.gridData)==null?void 0:O.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let w=G=>y==null?void 0:y.message.includes(G),b=y&&y instanceof pr,S=w(hh),E=y&&(w(Au)||S&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||S)&&e.retryOnInfraErrors,j=E&&e.hasMoreTimeoutRetries(),R=e.hasMoreRetries()&&!b&&!E,x=!g.success&&(R||j||D);try{let G=e.retryKey;g.testRetryKey=G;let z=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,x,z),await this.runTestCleanup(),x){if(j&&await e.startNewTimeoutRetry(),D){wt.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 X=(B=this.options.projectData)==null?void 0:B.projectId,fe=e.testResultId,Ze=e.testId;await jo(X,fe,Ze,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return R&&!D&&!j&&await e.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:G,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(x)}t(this.id,...r);return}catch(G){if(G instanceof qt)return;wt.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.
213
- Please make sure the CLI has stable access to the internet. ${Ec()?"(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:S}=Oc,E=g instanceof Error?g.message:g;return E.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),E.includes(gh)||E.includes(b)?{errorType:$n,reason:"timeout while getting device"}:E.includes(T)||E.includes(S)?{errorType:Uo,reason:"app doesn't exist on device"}:E.includes(w)?{errorType:Uo,reason:"app never started, check app permission or app activity"}:E.includes(y)?{errorType:Uo,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Uo,reason:E}},a=(g,y)=>{let T=this.options.mode===q.APPIUM?"device":"browser";if(!y&&_.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:QS,reason:i()};let w=g instanceof Error?g.message:g;if(w.includes(gh))return{errorType:$n,reason:`Test couldn't get ${T}`};if(w.includes(hh))return{errorType:$n,reason:"Test couldn't be started"};if(w.includes(Au)){if(!this.testRunTimeout)return{errorType:$n,reason:"Test timeout reached: test is too long"};let b=Pu.default.duration({milliseconds:this.testRunTimeout}),S=Math.floor(b.asMinutes()),E=b.asSeconds(),A=S>0?` ${S} min`:"",D=E>0?` ${E} sec`:"";return{errorType:$n,reason:`Test timeout reached (timeout:${A}${D}): test is too long`}}if(g instanceof pr&&g.type){if(g.type===Cu)return{errorType:Cu,reason:`Test couldn't get ${T} from grid - ${g.message}`};if(g.type===nr)return{errorType:nr,reason:`Failed to create new session - ${g.message}`}}return"type"in g&&g.type===ZS?{errorType:nr,reason:`Session terminated, this is often caused to connection
214
- problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:nr,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:nr,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:nr,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:nr,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:eE,reason:w}},l=async g=>{var S;let y=await Sc();!y&&_.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),wt.warn("error on run",{err:g});let T=(S=this.userData)==null?void 0:S.projectId,{errorType:w,reason:b}=this.options.mode===q.APPIUM?o(g):a(g,y);jo(T,this.testResultId,this.testId,{status:Hs.COMPLETED,success:!1,reason:b,errorType:w,testRetryKey:e.retryKey,setupStepResult:{status:Hs.COMPLETED,success:!1,reason:b,errorType:w}},e.remoteRunId),await n(tE(this.testId,this.testName,this.testResultId,b),g)},c=async g=>{var S;let y=this.testId,T=this.testResultId,w=(S=this.userData)==null?void 0:S.projectId,b=this.branch;if(!y||!T||!w||!b)return wt.warn("Test failed. Not enough data to recover results via API",{err:g}),l(g);try{let E=await kr(y,T,w,b);if(wt.warn("Test failed. Got results via API",{err:g,testResult:yh.default.omit(E,rE),resultId:T}),E&&E.status===Hs.COMPLETED&&!g.message.includes(Au))return await n(E);throw g}catch(E){return E!==g&&wt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:w,branch:b,err:E}),l(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===q.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&bs.joinToRemoteStep(this.testResultId),!d&&kt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==q.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),M("After onRunComplete"),t(this.id,...r)}catch(y){await c(y),t(this.id,...r)}finally{m||bs.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 wh,Th,Ts,ku=v(()=>{"use strict";F();wh=I(require("p-retry"));F();W();Y();Th=P("window-utils"),Ts=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 Th.warn("selenium navigation failed. retrying to navigate",{err:i}),await ce(1500),r(n-1);throw!i.seleniumStack&&o&&Th.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),ce(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ce(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 ce(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 It("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,wh.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var Ou,ws,_u=v(()=>{"use strict";W();Ou=P("cookies-utils"),ws=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 Ou.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw Ou.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw Ou.error("failed to remove cookie",{err:t}),t}}}});var Lu,$o,vh=v(()=>{"use strict";Lu=I(require("p-retry")),$o=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,Lu.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,Lu.default)(i,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.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 Sh(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 sE.warn("missing elementRect",Ih.omit(s,"image")),{};let{elementRect:o}=s,a=await Wo.Jimp.fromBuffer(Buffer.from(n[1],"base64")),l=o.left*r+i.left*r,c=o.top*r+i.top*r,d=o.width*r,m=o.height*r;l<0&&(d+=l,d=Math.max(d,0),l=0),c<0&&(m+=c,m=Math.max(m,0),c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new Du("height or width is equal or lower than zero");return{elementImage:await a.crop({x:l,y:c,w:d,h:m}).getBase64(Rh)}}async function nE(s,e){let t=new Wo.Jimp({width:s.width,height:s.height});for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await Wo.Jimp.fromBuffer(Buffer.from(i[1],"base64"));t.composite(o,n.position.left,n.position.top)}return await t.getBase64(Rh)}function iE(s,e){return nE(s,e)}async function oE(){}async function aE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await oE(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 Eh(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 Ih,Wo,sE,Rh,Du,Vo,xh=v(()=>{"use strict";Ih=I(require("lodash"));F();Wo=require("jimp");W();sE=P("image-capture-utils"),Rh="image/png",Du=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Vo=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 Sh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Eh(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 aE({screenImage:t.image,absoluteScreenHighlight:Eh(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=()=>ce(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 Sh({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 l(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)},(S,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)},(S,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(S=>b.map(E=>({scrollPos:{x:S.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:S.cropX,width:S.cropW,height:E.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),iE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var Ah,Ch,Go,Ho,Ph=v(()=>{"use strict";Ah=I(require("p-retry")),Ch=I(require("semver"));F();W();ku();vh();xh();we();Go=P("tab-service"),Ho=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),Go.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 l(c){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!c.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:l(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Ts(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Vo(t,a,new $o(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),l=n(o),c=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Z();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(c=>i[c].url);if(this.exactUrlMatch(t,r,o))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,o,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(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){Go.error("failed to get url or title",{err:i})}}catch(n){Go.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 ce(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]){Go.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,Ah.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=Ch.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 l,c;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((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var Nu,qo,Mu=v(()=>{"use strict";Nu=class{select(){return console.log(`
211
+ `,u=[],f=new Vg.Worker(m,{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};pt.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"?pt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):pt.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",()=>{pt.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 oe))throw h;return pt.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 DS(s){try{await jg.promises.rm(s,{recursive:!0,force:!0})}catch(e){pt.warn("failed to remove install npm packages folder",{err:e})}}function Gg(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function fs(s,e,t,r,n,i){let o=Gg(n,e,s,t),{data:a}=await NS(o,r,i);return a}async function gs(s,e,t,r,n,i,o,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||_.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=Lm(y.testimPackageLocalLocation);return[y.paramName,ms.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=Gg(o,n,e,i);if(c){let y=await xn(c);y&&(l=y)}Buffer.isBuffer(l)&&(pt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let f="data:,";return l==="data:"&&(pt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=f),{...await LS(u,t,r,s,m,a,l),nodeVersion:process.version}}async function NS(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Hg(),o=_.flags.reuseCliPkgInstallFolder.isEnabled()?n:ms.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Hc(o,r,a,t),pt.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=Om(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ms.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw pt.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await le(l(),t)}catch(c){throw c instanceof oe&&pt.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Hg(){return ms.join($g.tmpdir(),"/testim_local_packages")}function MS(){let s=Hg();return DS(s)}var jg,$g,ms,Wg,Vg,pt,hs=v(()=>{"use strict";jg=I(require("fs")),$g=I(require("os")),ms=I(require("path"));F();Zr();Wg=I(require("data-uri-to-buffer")),Vg=require("worker_threads");Y();W();ge();Zr();ue();pt=P("cli-service");MS().catch(s=>pt.warn("failed to clean local package folder",{err:s}))});var sr={};H(sr,{run:()=>FS});function US(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=_.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var FS,qg=v(()=>{"use strict";hs();Y();ue();FS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await gs(r,n,i,o,a,l,c,d,m,u);return f&&US({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof oe?new Error("Timeout while running action"):f}}});var lu={};H(lu,{run:()=>BS});var BS,zg=v(()=>{"use strict";hs();Y();BS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await fs(t,r,n,o,i,a),success:!0}}catch(l){if(l instanceof Rt)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof oe)return{success:!1,code:"timeout"};throw l}}});async function Jg(s,e,t,r){try{return await uu(s,e,t,r)}catch{Co.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function $S(s,e,t,r,n){return Co.info("finished to run remote step",{stepId:t,sessionId:n}),await Jg(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Kg(s,e,t,r,n){return Co.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Jg(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Yg(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(),l=t.id;Co.info("start play remote step",{stepType:o,stepId:l,sessionId:a});let c=jS[o];if(!c)return await Kg(n,r,l,`Failed to find step type ${o}`,a);try{let d=await c.run(e,t,i);return await $S(n,r,l,d,a)}catch(d){return await Kg(n,r,l,d.message,a)}}var Co,jS,Xg=v(()=>{"use strict";qg();ge();zg();W();Co=P("step-playback"),jS={"cli-validation-code-step":sr,"cli-wait-for-code-step":sr,"cli-action-code-step":sr,"cli-api-code-step":sr,"cli-condition-step":sr,"cli-download-code-step":sr,"node-package":lu}});var Zg={};H(Zg,{preloadTests:()=>Mn});async function Mn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await Bt(async()=>{let t=await se(s.testId,r=>Un({...e,testId:r}),{concurrency:2});return Qg.keyBy(t,"testData.id")},"loadTests",VS,[e,s.testId])()}var Qg,VS,Po=v(()=>{"use strict";Qg=I(require("lodash"));Yt();ge();F();VS=1e3*60*60*10});var pu,eh,Cr,GS,du,Tt,ko=v(()=>{"use strict";F();at();pu=I(require("ws")),eh=require("events");W();de();Cr=P("socket-service"),GS=5e3,du=class extends eh.EventEmitter{constructor(){super(...arguments);this.clientId=re();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Cr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),GS)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Cr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(yd);return At().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new pu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return Cr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{Cr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===pu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Cr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Cr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Cr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(l){n(l)&&i(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=o.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=re(),l={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",c=>c.id===a,o),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}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})}},Tt=new du});var rh,mu,HS,qS,zS,th,Oo,ys,fu=v(()=>{"use strict";rh=I(require("p-retry")),mu=I(require("socket.io-client"));de();F();W();HS=50,qS=10,zS=5e3,th=10*1e3,Oo=P("base socket service"),ys=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Oo.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{}Oo.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===qS&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=HS)throw new Error(`Can't connect to Testim Servers.
212
+ 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",()=>{Oo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:th,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${he}/${t}`,this._socket=mu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:th,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${he}/${t}`,this._socket=mu.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,rh.default)(()=>le(n(),zS),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Oo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var sh={};H(sh,{remoteStepServiceSocketIO:()=>KS});var gu,KS,nh=v(()=>{"use strict";fu();gu=class extends ys{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))}},KS=new gu});var ih={};H(ih,{remoteStepService:()=>bs});var hu,Fn,yu,bs,_o=v(()=>{"use strict";ko();ie();ue();({REMOTE_STEP_SAVED:hu}=xt),yu=class{async init(e){_.flags.useNewWSCLI.isEnabled()||(Fn=(await Promise.resolve().then(()=>(nh(),sh))).remoteStepServiceSocketIO,Fn.init(e))}joinToRemoteStep(e){return _.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:remoteStep`,{resultId:e},[hu]):Fn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(_.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:remoteStep`,[hu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Fn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return _.flags.useNewWSCLI.isEnabled()?(Tt.removeFilter(`${e}:remoteStep`,[hu]),Promise.resolve()):Fn.unlistenToRemoteStep(e)}},bs=new yu});var bu,Pr,oh=v(()=>{"use strict";fu();bu=class extends ys{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}},Pr=new bu});var ch={};H(ch,{testResultService:()=>kt});var ah,Tu,kt,Lo=v(()=>{"use strict";ah=require("events");ko();ie();ue();oh();Tu=class extends ah.EventEmitter{init(e){if(_.flags.useNewWSCLI.isEnabled()){Tt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return _.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(_.flags.useNewWSCLI.isEnabled()){Tt.removeFilter(`${e}:testResult`,[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(_.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:testResult`,[xt.TEST_RESULT_UPDATED,xt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!_.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},kt=new Tu});var uh,ph,dh,Se,JS,mh,lh,YS,Do,fh=v(()=>{"use strict";uh=I(require("lodash"));F();de();je();rs();at();ge();Xg();ph=I(require("p-retry")),dh=require("node:url");W();Po();ls();ie();_o();Lo();ge();Se=P("test-run-handler"),JS=3,mh=20*1e3,lh=s=>JSON.stringify(s).length<mh,YS="Test couldn't be started",Do=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 Sr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;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=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?Ys(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,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 Js(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Hr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?xi.FROM_DEVICE:xi.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 Un({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await At(),refreshToken:qi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Ed,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 zi()};if(this._options.disableMockNetwork&&yt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=lh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,l=this.testId;o?(Object.assign(t,{runData:i}),Se.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):Se.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${mh} 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 Mn(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 Se.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get 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&&lh(e))return;let r=async()=>{try{return await Su(this._options.project,this._testId,this._testResultId,e)}catch(o){return Se.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),vu(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===YS||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){M("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=o||{};M("before Runtime.evaluate"),await(0,ph.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return M("after Runtime.evaluate"),c.value}catch(o){throw Se.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 dh.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)){Se.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)&&(Se.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:l,branch:c,_options:{project:d}}=this;try{let m=await kr(a,l,d,c);n(m),r||setTimeout(o,3e3)}catch(m){Se.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else kt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await kr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Se.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Se.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Me.TEST_START_TIMEOUT_MSG)}catch(i){throw Se.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Me.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await kt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Se.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||kt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Se.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=uh.debounce(async()=>{try{await kt.joinToTestResult(this._testResultId,this.testId)}catch(o){Se.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await kr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Se.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"?(Se.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 Se.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)kt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await wu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Se.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Se.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&kt.off("socket-connected",e)}}listenToRemoteStep(e){bs.listenToRemoteStep(this.testResultId,t=>{Yg(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:JS;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 No,gh=v(()=>{"use strict";fh();No=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Do(e,t,l,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function yh(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Ru({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 Eu(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 Iu(s,e){let t=s.mode===q.EXTENSION?Or:Bn,r=hh.difference(zs(s,e),t);if(r.length>0)throw yt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var hh,Or,Bn,Mo=v(()=>{"use strict";hh=I(require("lodash"));F();rs();ge();Y();ie();Or=["edge-chromium","chrome"],Bn=[...Or,"firefox","safari","safari technology preview"]});var XS,QS,ZS,jn,xu=v(()=>{"use strict";ts();os();W();XS=P("worker-utils"),QS=async(s,e,t)=>{e&&await ll(s,t)},ZS=async(s,e,t)=>{await Dl(s,e,t)},jn=async(s,e,t,r,n,i)=>{XS.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await QS(s,e,t),n==="redis"&&await ZS(s,r,t)}}});function sE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Fo,wh,Bo,Pu,vh,wt,bh,Th,Au,$n,eE,Cu,tE,nr,rE,Uo,nE,Ot,Wn=v(()=>{"use strict";Fo=I(require("ms")),wh=I(require("lodash")),Bo=I(require("p-retry")),Pu=I(require("dayjs")),vh=I(require("dayjs/plugin/duration"));F();je();ts();os();ge();W();xu();Pt();Eo();ue();_o();Lo();at();Ve();ie();Y();Pu.default.extend(vh.default);wt=P("base-worker"),{GET_BROWSER_TIMEOUT_MSG:bh,TEST_START_TIMEOUT_MSG:Th,TEST_COMPLETE_TIMEOUT_MSG:Au}=Me,{SETUP_TIMEOUT:$n,NETWORK_ERROR:eE,GRID_ERROR:Cu,BROWSER_CLOSED:tE,SELENIUM_ERROR:nr,UNKNOWN_ERROR:rE,MOBILE_SESSION_ERROR:Uo}=qs;nE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,i,o,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;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 lf(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 Bs(!0)}async getBrowserOnce(e,t,r,n){throw new Bs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.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:me.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=qr(_,(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:me.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=_.flags.increaseTDCRequestTimeout.isEnabled(),r=e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN,n=mr(_.flags.appiumConnectionRequestTimeout.getValue(),(0,Fo.default)("2m")),i=mr(_.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===L.BROWSERSTACK||t&&r?o+(0,Fo.default)("10m"):o+(0,Fo.default)("1m")}getSessionTimeout(){if(Jt(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,Bo.default)(async()=>{let n=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Me.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,Bo.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(Nf(o,a,this.id),this.options.getBrowserTimeout,Me.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 zt?wt.info("could not get grid slot due to concurrency issue",r):wt.error("error getting grid slot",{error:e,...r}),await ce(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let l=this.options.getBrowserRetries-o;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,Bo.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await uf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c,M("before getBrowserOnce");let f=await le(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Me.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw wt.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,++c),m.onDone(),!(u instanceof It)&&this.options.mode!==q.APPIUM&&await ce(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(o){throw await jn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[It,Wr].some(a=>o instanceof a)?o:o instanceof rt?new pr(o,Cu):new pr(o,nr)}return n}async runTest(e,t,r){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Jt(this.options)&&this.handleMobileTest(e);if(o)return o;M("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await At(),await this.runTestOnce(e,c)}finally{await jn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var O,B;if(Ye(g,this.options)||qr(_,(O=this.options.gridData)==null?void 0:O.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let w=G=>y==null?void 0:y.message.includes(G),b=y&&y instanceof pr,S=w(Th),E=y&&(w(Au)||S&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||S)&&e.retryOnInfraErrors,j=E&&e.hasMoreTimeoutRetries(),R=e.hasMoreRetries()&&!b&&!E,x=!g.success&&(R||j||D);try{let G=e.retryKey;g.testRetryKey=G;let z=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,x,z),await this.runTestCleanup(),x){if(j&&await e.startNewTimeoutRetry(),D){wt.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 X=(B=this.options.projectData)==null?void 0:B.projectId,fe=e.testResultId,Ze=e.testId;await jo(X,fe,Ze,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return R&&!D&&!j&&await e.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:G,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(x)}t(this.id,...r);return}catch(G){if(G instanceof qt)return;wt.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.
213
+ Please make sure the CLI has stable access to the internet. ${Ec()?"(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:S}=Oc,E=g instanceof Error?g.message:g;return E.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),E.includes(bh)||E.includes(b)?{errorType:$n,reason:"timeout while getting device"}:E.includes(T)||E.includes(S)?{errorType:Uo,reason:"app doesn't exist on device"}:E.includes(w)?{errorType:Uo,reason:"app never started, check app permission or app activity"}:E.includes(y)?{errorType:Uo,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Uo,reason:E}},a=(g,y)=>{let T=this.options.mode===q.APPIUM?"device":"browser";if(!y&&_.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:eE,reason:i()};let w=g instanceof Error?g.message:g;if(w.includes(bh))return{errorType:$n,reason:`Test couldn't get ${T}`};if(w.includes(Th))return{errorType:$n,reason:"Test couldn't be started"};if(w.includes(Au)){if(!this.testRunTimeout)return{errorType:$n,reason:"Test timeout reached: test is too long"};let b=Pu.default.duration({milliseconds:this.testRunTimeout}),S=Math.floor(b.asMinutes()),E=b.asSeconds(),A=S>0?` ${S} min`:"",D=E>0?` ${E} sec`:"";return{errorType:$n,reason:`Test timeout reached (timeout:${A}${D}): test is too long`}}if(g instanceof pr&&g.type){if(g.type===Cu)return{errorType:Cu,reason:`Test couldn't get ${T} from grid - ${g.message}`};if(g.type===nr)return{errorType:nr,reason:`Failed to create new session - ${g.message}`}}return"type"in g&&g.type===tE?{errorType:nr,reason:`Session terminated, this is often caused to connection
214
+ problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:nr,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:nr,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:nr,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:nr,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:rE,reason:w}},l=async g=>{var S;let y=await Sc();!y&&_.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),wt.warn("error on run",{err:g});let T=(S=this.userData)==null?void 0:S.projectId,{errorType:w,reason:b}=this.options.mode===q.APPIUM?o(g):a(g,y);jo(T,this.testResultId,this.testId,{status:Hs.COMPLETED,success:!1,reason:b,errorType:w,testRetryKey:e.retryKey,setupStepResult:{status:Hs.COMPLETED,success:!1,reason:b,errorType:w}},e.remoteRunId),await n(sE(this.testId,this.testName,this.testResultId,b),g)},c=async g=>{var S;let y=this.testId,T=this.testResultId,w=(S=this.userData)==null?void 0:S.projectId,b=this.branch;if(!y||!T||!w||!b)return wt.warn("Test failed. Not enough data to recover results via API",{err:g}),l(g);try{let E=await kr(y,T,w,b);if(wt.warn("Test failed. Got results via API",{err:g,testResult:wh.default.omit(E,nE),resultId:T}),E&&E.status===Hs.COMPLETED&&!g.message.includes(Au))return await n(E);throw g}catch(E){return E!==g&&wt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:w,branch:b,err:E}),l(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===q.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&bs.joinToRemoteStep(this.testResultId),!d&&kt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==q.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),M("After onRunComplete"),t(this.id,...r)}catch(y){await c(y),t(this.id,...r)}finally{m||bs.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 Eh,Sh,Ts,ku=v(()=>{"use strict";F();Eh=I(require("p-retry"));F();W();Y();Sh=P("window-utils"),Ts=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 Sh.warn("selenium navigation failed. retrying to navigate",{err:i}),await ce(1500),r(n-1);throw!i.seleniumStack&&o&&Sh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),ce(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ce(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 ce(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 It("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Eh.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var Ou,ws,_u=v(()=>{"use strict";W();Ou=P("cookies-utils"),ws=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 Ou.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw Ou.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw Ou.error("failed to remove cookie",{err:t}),t}}}});var Lu,$o,Ih=v(()=>{"use strict";Lu=I(require("p-retry")),$o=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,Lu.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,Lu.default)(i,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.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 Rh(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 iE.warn("missing elementRect",Ah.omit(s,"image")),{};let{elementRect:o}=s,a=await Wo.Jimp.fromBuffer(Buffer.from(n[1],"base64")),l=o.left*r+i.left*r,c=o.top*r+i.top*r,d=o.width*r,m=o.height*r;l<0&&(d+=l,d=Math.max(d,0),l=0),c<0&&(m+=c,m=Math.max(m,0),c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new Du("height or width is equal or lower than zero");return{elementImage:await a.crop({x:l,y:c,w:d,h:m}).getBase64(Ch)}}async function oE(s,e){let t=new Wo.Jimp({width:s.width,height:s.height});for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await Wo.Jimp.fromBuffer(Buffer.from(i[1],"base64"));t.composite(o,n.position.left,n.position.top)}return await t.getBase64(Ch)}function aE(s,e){return oE(s,e)}async function cE(){}async function lE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await cE(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 xh(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 Ah,Wo,iE,Ch,Du,Vo,Ph=v(()=>{"use strict";Ah=I(require("lodash"));F();Wo=require("jimp");W();iE=P("image-capture-utils"),Ch="image/png",Du=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Vo=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 Rh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:xh(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 lE({screenImage:t.image,absoluteScreenHighlight:xh(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=()=>ce(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 Rh({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 l(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)},(S,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)},(S,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(S=>b.map(E=>({scrollPos:{x:S.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:S.cropX,width:S.cropW,height:E.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),aE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var kh,Oh,Go,Ho,_h=v(()=>{"use strict";kh=I(require("p-retry")),Oh=I(require("semver"));F();W();ku();Ih();Ph();we();Go=P("tab-service"),Ho=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),Go.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 l(c){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!c.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:l(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Ts(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Vo(t,a,new $o(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),l=n(o),c=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Z();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(c=>i[c].url);if(this.exactUrlMatch(t,r,o))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,o,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(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){Go.error("failed to get url or title",{err:i})}}catch(n){Go.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 ce(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]){Go.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,kh.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=Oh.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 l,c;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((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var Nu,qo,Mu=v(()=>{"use strict";Nu=class{select(){return console.log(`
215
215
  internal error - cant use port selector in selenium!!!!
216
- `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},qo=new Nu});var Vn,zo,Ko=v(()=>{"use strict";_u();F();we();Vn={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"},zo=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Xs;this.getLinksFromUnescapeHTML=Qs;this.cookieUtils=new ws(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 Oh(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=kh(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,i){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:l}=Z();if(l.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw cE.error(u),new Error(u)}let c=await s.switchToLocatedFrame(a),d=kh(c.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:c.value,frameLocateResultUrl:m}}async locate(r,n,i,o,a,l){let c=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${n}`;let d=await c.locate(r,i,r.targetId);d.isVisible=!0;let m=await c.handleLocateResult(d,l,r).catch(()=>{throw new Error("")}),{locatedElement:u}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},c.addFrameDataToContext&&c.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,i,o){let a=_.flags.enableFrameSwitchOptimization.isEnabled(),c=i.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=c&&c.stepId===r.id&&c.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),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 cE,lE,kh,_h=v(()=>{"use strict";W();ue();we();jr();cE=P("frame-locator"),lE="ELEMENT",kh=s=>s?s[lE]||s[Gt]:null});var Jo,Uu=v(()=>{"use strict";de();Jo=()=>{try{if(gd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var V,pe=v(()=>{"use strict";we();V=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 pE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:_.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?_.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function dE(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 Lh.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:l,codeSnippets:c,visibilityUtils:d,positionUtils:m}=Z();if(pE(n,d,m,s))return s.isVisible(e.seleniumElement);if(s.getIgnoreVisibility())return{visible:!0,invisibleReason:"visibility is ignored"};if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||l.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=c.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(E){throw _r.error("failed to execute getVisibilityCode",{err:E}),E}let{value:T}=y||{},w=T.elementVisibilityInfo||uE,[b,S]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(w,n,S,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=Z();await s.execute(r(t))}}}var Lh,_r,uE,Gn,Dh=v(()=>{"use strict";pe();W();ue();we();Lh=require("linkedom"),_r=P("locate-step-action"),uE={opacity:1,clientRects:{}};Gn=class extends V{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return dE(e)}static getFrameIdByTestimFrameId(){throw _r.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw _r.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw _r.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw _r.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw _r.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw _r.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Nh={};H(Nh,{scroll:()=>mE});var mE,Mh=v(()=>{"use strict";mE=function(s,e,t,r,n,i,o,a){function l(w,b){if(!b)return{success:!1};elementScrollTo(b,w.x,w.y);let S=b.scrollLeft,E=b.scrollTop;return{success:Math.abs(E-w.y)<1&&Math.abs(S-w.x)<1,actualX:S,actualY:E}}function c(w,b){if(!t)return{x:n,y:i};let S=getLocatedElement(b);if(r&&!S)return{x:w.scrollWidth,y:w.scrollHeight};if(!S)throw new Error("could not find target element");let E=S.getBoundingClientRect(),A=0,D=0,j=Math.max(window.innerHeight-(E.height+10),0),R=Math.max(window.innerWidth-(E.width+10),0);return A=a?w.scrollTop+E.top-Math.min(i,j):w.scrollTop,D=o?w.scrollLeft+E.left-Math.min(n,R):w.scrollLeft,{x:Math.round(D),y:Math.round(A)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=c(m,e),h=l(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=c(m,e),h=l(f,m));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let w=T.getBoundingClientRect();g=w.left,y=w.top}return{success:h.success,actualX:g,actualY:y}}});var Yo,Uh=v(()=>{"use strict";pe();Yo=class extends V{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)),l=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:c}=await Promise.resolve().then(()=>(Mh(),Nh)),d=`
216
+ `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},qo=new Nu});var Vn,zo,Ko=v(()=>{"use strict";_u();F();we();Vn={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"},zo=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Xs;this.getLinksFromUnescapeHTML=Qs;this.cookieUtils=new ws(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 Dh(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=Lh(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,i){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:l}=Z();if(l.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw uE.error(u),new Error(u)}let c=await s.switchToLocatedFrame(a),d=Lh(c.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:c.value,frameLocateResultUrl:m}}async locate(r,n,i,o,a,l){let c=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${n}`;let d=await c.locate(r,i,r.targetId);d.isVisible=!0;let m=await c.handleLocateResult(d,l,r).catch(()=>{throw new Error("")}),{locatedElement:u}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},c.addFrameDataToContext&&c.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,i,o){let a=_.flags.enableFrameSwitchOptimization.isEnabled(),c=i.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=c&&c.stepId===r.id&&c.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),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 uE,pE,Lh,Nh=v(()=>{"use strict";W();ue();we();jr();uE=P("frame-locator"),pE="ELEMENT",Lh=s=>s?s[pE]||s[Gt]:null});var Jo,Uu=v(()=>{"use strict";de();Jo=()=>{try{if(hd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var V,pe=v(()=>{"use strict";we();V=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 mE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:_.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?_.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function fE(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 Mh.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:l,codeSnippets:c,visibilityUtils:d,positionUtils:m}=Z();if(mE(n,d,m,s))return s.isVisible(e.seleniumElement);if(s.getIgnoreVisibility())return{visible:!0,invisibleReason:"visibility is ignored"};if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||l.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=c.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(E){throw _r.error("failed to execute getVisibilityCode",{err:E}),E}let{value:T}=y||{},w=T.elementVisibilityInfo||dE,[b,S]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(w,n,S,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=Z();await s.execute(r(t))}}}var Mh,_r,dE,Gn,Uh=v(()=>{"use strict";pe();W();ue();we();Mh=require("linkedom"),_r=P("locate-step-action"),dE={opacity:1,clientRects:{}};Gn=class extends V{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return fE(e)}static getFrameIdByTestimFrameId(){throw _r.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw _r.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw _r.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw _r.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw _r.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw _r.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Fh={};H(Fh,{scroll:()=>gE});var gE,Bh=v(()=>{"use strict";gE=function(s,e,t,r,n,i,o,a){function l(w,b){if(!b)return{success:!1};elementScrollTo(b,w.x,w.y);let S=b.scrollLeft,E=b.scrollTop;return{success:Math.abs(E-w.y)<1&&Math.abs(S-w.x)<1,actualX:S,actualY:E}}function c(w,b){if(!t)return{x:n,y:i};let S=getLocatedElement(b);if(r&&!S)return{x:w.scrollWidth,y:w.scrollHeight};if(!S)throw new Error("could not find target element");let E=S.getBoundingClientRect(),A=0,D=0,j=Math.max(window.innerHeight-(E.height+10),0),R=Math.max(window.innerWidth-(E.width+10),0);return A=a?w.scrollTop+E.top-Math.min(i,j):w.scrollTop,D=o?w.scrollLeft+E.left-Math.min(n,R):w.scrollLeft,{x:Math.round(D),y:Math.round(A)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=c(m,e),h=l(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=c(m,e),h=l(f,m));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let w=T.getBoundingClientRect();g=w.left,y=w.top}return{success:h.success,actualX:g,actualY:y}}});var Yo,jh=v(()=>{"use strict";pe();Yo=class extends V{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)),l=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:c}=await Promise.resolve().then(()=>(Bh(),Fh)),d=`
217
217
  const getLocatedElement = ${n.getLocatedElementCode};
218
218
  const elementScrollTo = ${l.toString()};
219
219
  const scroll = ${c.toString()};
220
220
  return scroll.apply(null, arguments)
221
- `;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var Fh,Bh=v(()=>{"use strict";Fh=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,l){e[t(a)]=l},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,l){let c=document.createEvent("CustomEvent");c.initCustomEvent(l,!0,!0,null),Object.assign(c,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(c):a.fireEvent&&a.fireEvent(`on${l}`,c)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var jh,$h=v(()=>{"use strict";jh=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(x){e({status:"done",result:x,success:!0})}function a(x){x||={},e({status:"failed",result:x,success:!1,keep:!0})}function l(x){return x!=null&&x.toLowerCase?(x=x.toLowerCase(),x==="text"?"text/plain":x==="url"?"text/uri-list":x):x}function c(){try{return new DataTransfer}catch{return{data:{},setData(O,B){i[l(O)]=B},getData(O){return i[l(O)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(x){let O=x;for(;O&&O!==document.documentElement;){if(O.draggable)return O;O=O.parentElement}return null}function h(x,O,B){let G=O.element,{dispatchDragEventsOnClosestDraggable:z}=B;if(d.includes(x.type)&&z){if(!G&&O.lastDraggedElement)return O.lastDraggedElement;let X=f(G);if(X)return O.lastDraggedElement=X,X}return G}function g(x,O,B){function G(St,Br,k){return k>St&&k<Br}let z=x.pointerPosition||{};if(O)return{x:z.originX||0,y:z.originY||0};let X=B.getBoundingClientRect(),fe=z.originX&&G(X.left,X.left+X.width,z.originX)?z.originX:X.left+X.width/2,Ze=z.originY&&G(X.top,X.top+X.height,z.originY)?z.originY:X.top+X.height/2;return{x:fe,y:Ze}}function y(x,O,B){let G=(O==null?void 0:O.modifiers)||{},z=g(x,B.isDrag,B.element),X=(O==null?void 0:O.button)||0,fe=x.event;return m.includes(fe)?w(fe,G,z.x,z.y,X):u.includes(fe)?S(fe,G,z.x,z.y):b(fe,G,z.x,z.y,X)}function T(x,O,B){return{screenX:0,screenY:0,clientX:O,clientY:B,ctrlKey:Boolean(x.ctrl),altKey:Boolean(x.alt),shiftKey:Boolean(x.shift),metaKey:Boolean(x.meta),bubbles:!0,cancelable:!0,composed:!0}}function w(x,O,B,G,z){if(n){let fe=T(O,B,G);return fe.pointerType="mouse",fe.isPrimary=!0,new window.PointerEvent(x,fe)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(x,!0,!0,document.defaultView,1,0,0,B,G,Boolean(O.ctrl),Boolean(O.alt),Boolean(O.shift),Boolean(O.meta),z,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function b(x,O,B,G,z){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(x,!0,!0,document.defaultView,1,0,0,B,G,Boolean(O.ctrl),Boolean(O.alt),Boolean(O.shift),Boolean(O.meta),z,document.body?document.body.parentNode:document.documentElement),X}function S(x,O,B,G){if(x==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let fe=document.createEvent("CustomEvent");return fe.initCustomEvent(x,!0,!0,null),Object.assign(fe,{dataTransfer:window.TSTA.dataTransfer}),fe}let z=T(O,B,G),X=new window.DragEvent(x,z);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function E(x,O,B){let G=h(x,O,B);G==null||G.dispatchEvent(x)}function A(x,O){function B(){return x.event==="click"&&O.isDrag&&!O.allEventsOnSameElement}return B()}function D(x,O,B){if(B){let G=Math.min(B.timeStamp-O.timeStamp,40);setTimeout(()=>{j(x)},G)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function j(x){let O,B=x.events[x.eventIndex],G=x.events[++x.eventIndex];try{x.element=getLocatedElement(B.locatedElement),O=y(B,s,x)}catch(z){return a(`exception in get event in drag step:${z.message}`)}if(A(B,x))return D(x,B,G);if(O)try{E(O,x,B)}catch(z){return a(`exception in executeEvent in drag step:${z.message}`)}else return a(`cannot execute event ${B.event}`);D(x,B,G)}let R={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{j(R)}catch(x){a(x)}},0)}});var Wh={};H(Wh,{doClick:()=>fE});var fE,Vh=v(()=>{"use strict";fE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,S){var D;function E(j){function R(){return i(j).find(B=>[...B.classList||[]].includes("Select-control"))}function x(){let B=R();return B?B.querySelector("input"):null}let O=x();O==null||O.focus()}let A=(D=b.quirks)==null?void 0:D.isReactSelect;S.type==="mousedown"&&A&&E(b.element)}function n(b,S){var A;let E=(A=b.quirks)==null?void 0:A.isCKEditorFrame;S.type==="click"&&E&&document.body.focus()}function i(b){let S=[];for(;b!=null&&b.parentNode;)S.push(b),b=b.parentNode;return S}function o(b){let S={status:"done",result:b,success:!0,...w.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(S)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let S=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");S.initEvent("mouseover",!0,!0),b.dispatchEvent(S)}function c(b){let S={},E=b.getBoundingClientRect(),A=E.left+E.width/2,D=E.top+E.height/2,x=f("mousemove",S,A,D,0);b.dispatchEvent(x)}function d(b,S){function E(x,O,B){return B>x&&B<O}let A=b.pointerPosition||{},D=S.getBoundingClientRect(),j=A.originX&&E(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,R=A.originY&&E(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:j,y:R}}function m(b,S,E){return{screenX:0,screenY:0,clientX:S,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,S,E,A){if(!window.PointerEvent)return;let D=m(S,E,A);return D.pointerType="mouse",D.isPrimary=!0,new window.PointerEvent(b,D)}function f(b,S,E,A,D){let j=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return j.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement),j}function h(b,S){let E=["pointerup","pointerdown","pointermove"],A=S.modifiers||{},D=d(b,S.element),j=S.button||0,R=b.event;return E.includes(R)?u(R,A,D.x,D.y):f(R,A,D.x,D.y,j)}function g(){var S;let b=document.activeElement;for(;(S=b.shadowRoot)!=null&&S.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(S=>{try{return h(S,b)}catch{return}}).filter(Boolean).forEach(S=>{b.element.dispatchEvent(S),r(b,S),n(b,S)}),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}l(w.element),c(w.element);try{y(w);let b=g(),S=w.quirks,E=S==null?void 0:S.isReactSelect,A=S==null?void 0:S.isCKEditorFrame;!E&&!A&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var Gh={};H(Gh,{doDragPath:()=>gE});var gE,Hh=v(()=>{"use strict";gE=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 S=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");S.initEvent("mouseover",!0,!0),b.dispatchEvent(S)}function l(b){let S={},E=b.getBoundingClientRect(),A=E.left+E.width/2,D=E.top+E.height/2,x=u("mousemove",S,A,D,0);b.dispatchEvent(x)}function c(b,S){function E(x,O,B){return B>x&&B<O}let A=b.pointerPosition||{};if(w.isDrag)return{x:A.originX||0,y:A.originY||0};let D=S.getBoundingClientRect(),j=A.originX&&E(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,R=A.originY&&E(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:j,y:R}}function d(b,S,E){return{screenX:0,screenY:0,clientX:S,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 m(b,S,E,A,D){if(r){let R=d(S,E,A);return R.pointerType="mouse",R.isPrimary=!0,new window.PointerEvent(b,R)}let j=document.createEvent("PointerEvent");return j.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),j}function u(b,S,E,A,D){let j=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return j.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement),j}function f(b,S){let E=["pointerup","pointerdown","pointermove"],A=S.modifiers||{},D=c(b,S.element),j=S.button||0,R=b.event;return E.includes(R)?m(R,A,D.x,D.y,j):u(R,A,D.x,D.y,j)}function h(b,S){function E(){return b.event==="click"&&S.isDrag&&!S.allEventsOnSameElement}return E()}function g(b,S,E){try{let A=f(S.events[b],S);h(A,S)||S.element.dispatchEvent(A)}catch{}if(b+1===S.events.length)E();else{let A=Math.min(S.events[b+1].timeStamp-S.events[b].timeStamp,n);setTimeout(()=>{g(b+1,S,E)},A)}}function y(b,S){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),S()})}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),l(w.element),y(w,()=>{i()})}});var Hn,Xo,qh=v(()=>{"use strict";Hn=I(require("lodash"));pe();Bh();ue();$h();Xo=class extends V{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Vh(),Wh)),Promise.resolve().then(()=>(_n(),On))]),c=`
221
+ `;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var $h,Wh=v(()=>{"use strict";$h=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,l){e[t(a)]=l},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,l){let c=document.createEvent("CustomEvent");c.initCustomEvent(l,!0,!0,null),Object.assign(c,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(c):a.fireEvent&&a.fireEvent(`on${l}`,c)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var Vh,Gh=v(()=>{"use strict";Vh=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(x){e({status:"done",result:x,success:!0})}function a(x){x||={},e({status:"failed",result:x,success:!1,keep:!0})}function l(x){return x!=null&&x.toLowerCase?(x=x.toLowerCase(),x==="text"?"text/plain":x==="url"?"text/uri-list":x):x}function c(){try{return new DataTransfer}catch{return{data:{},setData(O,B){i[l(O)]=B},getData(O){return i[l(O)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(x){let O=x;for(;O&&O!==document.documentElement;){if(O.draggable)return O;O=O.parentElement}return null}function h(x,O,B){let G=O.element,{dispatchDragEventsOnClosestDraggable:z}=B;if(d.includes(x.type)&&z){if(!G&&O.lastDraggedElement)return O.lastDraggedElement;let X=f(G);if(X)return O.lastDraggedElement=X,X}return G}function g(x,O,B){function G(St,Br,k){return k>St&&k<Br}let z=x.pointerPosition||{};if(O)return{x:z.originX||0,y:z.originY||0};let X=B.getBoundingClientRect(),fe=z.originX&&G(X.left,X.left+X.width,z.originX)?z.originX:X.left+X.width/2,Ze=z.originY&&G(X.top,X.top+X.height,z.originY)?z.originY:X.top+X.height/2;return{x:fe,y:Ze}}function y(x,O,B){let G=(O==null?void 0:O.modifiers)||{},z=g(x,B.isDrag,B.element),X=(O==null?void 0:O.button)||0,fe=x.event;return m.includes(fe)?w(fe,G,z.x,z.y,X):u.includes(fe)?S(fe,G,z.x,z.y):b(fe,G,z.x,z.y,X)}function T(x,O,B){return{screenX:0,screenY:0,clientX:O,clientY:B,ctrlKey:Boolean(x.ctrl),altKey:Boolean(x.alt),shiftKey:Boolean(x.shift),metaKey:Boolean(x.meta),bubbles:!0,cancelable:!0,composed:!0}}function w(x,O,B,G,z){if(n){let fe=T(O,B,G);return fe.pointerType="mouse",fe.isPrimary=!0,new window.PointerEvent(x,fe)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(x,!0,!0,document.defaultView,1,0,0,B,G,Boolean(O.ctrl),Boolean(O.alt),Boolean(O.shift),Boolean(O.meta),z,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function b(x,O,B,G,z){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(x,!0,!0,document.defaultView,1,0,0,B,G,Boolean(O.ctrl),Boolean(O.alt),Boolean(O.shift),Boolean(O.meta),z,document.body?document.body.parentNode:document.documentElement),X}function S(x,O,B,G){if(x==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let fe=document.createEvent("CustomEvent");return fe.initCustomEvent(x,!0,!0,null),Object.assign(fe,{dataTransfer:window.TSTA.dataTransfer}),fe}let z=T(O,B,G),X=new window.DragEvent(x,z);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function E(x,O,B){let G=h(x,O,B);G==null||G.dispatchEvent(x)}function A(x,O){function B(){return x.event==="click"&&O.isDrag&&!O.allEventsOnSameElement}return B()}function D(x,O,B){if(B){let G=Math.min(B.timeStamp-O.timeStamp,40);setTimeout(()=>{j(x)},G)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function j(x){let O,B=x.events[x.eventIndex],G=x.events[++x.eventIndex];try{x.element=getLocatedElement(B.locatedElement),O=y(B,s,x)}catch(z){return a(`exception in get event in drag step:${z.message}`)}if(A(B,x))return D(x,B,G);if(O)try{E(O,x,B)}catch(z){return a(`exception in executeEvent in drag step:${z.message}`)}else return a(`cannot execute event ${B.event}`);D(x,B,G)}let R={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{j(R)}catch(x){a(x)}},0)}});var Hh={};H(Hh,{doClick:()=>hE});var hE,qh=v(()=>{"use strict";hE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,S){var D;function E(j){function R(){return i(j).find(B=>[...B.classList||[]].includes("Select-control"))}function x(){let B=R();return B?B.querySelector("input"):null}let O=x();O==null||O.focus()}let A=(D=b.quirks)==null?void 0:D.isReactSelect;S.type==="mousedown"&&A&&E(b.element)}function n(b,S){var A;let E=(A=b.quirks)==null?void 0:A.isCKEditorFrame;S.type==="click"&&E&&document.body.focus()}function i(b){let S=[];for(;b!=null&&b.parentNode;)S.push(b),b=b.parentNode;return S}function o(b){let S={status:"done",result:b,success:!0,...w.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(S)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let S=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");S.initEvent("mouseover",!0,!0),b.dispatchEvent(S)}function c(b){let S={},E=b.getBoundingClientRect(),A=E.left+E.width/2,D=E.top+E.height/2,x=f("mousemove",S,A,D,0);b.dispatchEvent(x)}function d(b,S){function E(x,O,B){return B>x&&B<O}let A=b.pointerPosition||{},D=S.getBoundingClientRect(),j=A.originX&&E(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,R=A.originY&&E(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:j,y:R}}function m(b,S,E){return{screenX:0,screenY:0,clientX:S,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,S,E,A){if(!window.PointerEvent)return;let D=m(S,E,A);return D.pointerType="mouse",D.isPrimary=!0,new window.PointerEvent(b,D)}function f(b,S,E,A,D){let j=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return j.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement),j}function h(b,S){let E=["pointerup","pointerdown","pointermove"],A=S.modifiers||{},D=d(b,S.element),j=S.button||0,R=b.event;return E.includes(R)?u(R,A,D.x,D.y):f(R,A,D.x,D.y,j)}function g(){var S;let b=document.activeElement;for(;(S=b.shadowRoot)!=null&&S.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(S=>{try{return h(S,b)}catch{return}}).filter(Boolean).forEach(S=>{b.element.dispatchEvent(S),r(b,S),n(b,S)}),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}l(w.element),c(w.element);try{y(w);let b=g(),S=w.quirks,E=S==null?void 0:S.isReactSelect,A=S==null?void 0:S.isCKEditorFrame;!E&&!A&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var zh={};H(zh,{doDragPath:()=>yE});var yE,Kh=v(()=>{"use strict";yE=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 S=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");S.initEvent("mouseover",!0,!0),b.dispatchEvent(S)}function l(b){let S={},E=b.getBoundingClientRect(),A=E.left+E.width/2,D=E.top+E.height/2,x=u("mousemove",S,A,D,0);b.dispatchEvent(x)}function c(b,S){function E(x,O,B){return B>x&&B<O}let A=b.pointerPosition||{};if(w.isDrag)return{x:A.originX||0,y:A.originY||0};let D=S.getBoundingClientRect(),j=A.originX&&E(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,R=A.originY&&E(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:j,y:R}}function d(b,S,E){return{screenX:0,screenY:0,clientX:S,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 m(b,S,E,A,D){if(r){let R=d(S,E,A);return R.pointerType="mouse",R.isPrimary=!0,new window.PointerEvent(b,R)}let j=document.createEvent("PointerEvent");return j.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),j}function u(b,S,E,A,D){let j=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return j.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,A,Boolean(S.ctrl),Boolean(S.alt),Boolean(S.shift),Boolean(S.meta),D,document.body?document.body.parentNode:document.documentElement),j}function f(b,S){let E=["pointerup","pointerdown","pointermove"],A=S.modifiers||{},D=c(b,S.element),j=S.button||0,R=b.event;return E.includes(R)?m(R,A,D.x,D.y,j):u(R,A,D.x,D.y,j)}function h(b,S){function E(){return b.event==="click"&&S.isDrag&&!S.allEventsOnSameElement}return E()}function g(b,S,E){try{let A=f(S.events[b],S);h(A,S)||S.element.dispatchEvent(A)}catch{}if(b+1===S.events.length)E();else{let A=Math.min(S.events[b+1].timeStamp-S.events[b].timeStamp,n);setTimeout(()=>{g(b+1,S,E)},A)}}function y(b,S){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),S()})}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),l(w.element),y(w,()=>{i()})}});var Hn,Xo,Jh=v(()=>{"use strict";Hn=I(require("lodash"));pe();Wh();ue();Gh();Xo=class extends V{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(qh(),Hh)),Promise.resolve().then(()=>(_n(),On))]),c=`
222
222
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
223
223
  var dispatchFocus = ${l.toString()};
224
224
  var doClick = ${a.toString()};
225
225
  var eventData = arguments[0];
226
226
  var done = arguments[1];
227
227
  return doClick.call(null, eventData, done);
228
- `;try{return(d=(await this.driver.executeCodeAsync(c,n,o)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var l;let e=(l=this.step.events[0])==null?void 0:l.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=Hn.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:n}=this.step,i=e.find(c=>["mousedown","pointerdown"].includes(c.event));if(i){let c=e.indexOf(i);e.splice(c,0,this.generateEventOfType(i,"mouseover"))}let{recordPointerMoveEvents:o=!1}=this.context.project.defaults||{},a=e.find(c=>c.event==="mouseup")||o&&e.find(c=>c.event==="pointerup"),l=Number(Hn.findLastIndex(e,c=>c.event==="mousemove")||o&&Hn.findLastIndex(e,c=>c.event==="pointermove"));a&&l>0&&!t&&e.splice(l+1,0,this.generateEventOfType(a,"mouseover")),r&&!n&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var d,m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3;if(!((d=e.events)!=null&&d.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let i=e.events,o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Hh(),Gh)),Promise.resolve().then(()=>(_n(),On))]),c=`
228
+ `;try{return(d=(await this.driver.executeCodeAsync(c,n,o)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var l;let e=(l=this.step.events[0])==null?void 0:l.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=Hn.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:n}=this.step,i=e.find(c=>["mousedown","pointerdown"].includes(c.event));if(i){let c=e.indexOf(i);e.splice(c,0,this.generateEventOfType(i,"mouseover"))}let{recordPointerMoveEvents:o=!1}=this.context.project.defaults||{},a=e.find(c=>c.event==="mouseup")||o&&e.find(c=>c.event==="pointerup"),l=Number(Hn.findLastIndex(e,c=>c.event==="mousemove")||o&&Hn.findLastIndex(e,c=>c.event==="pointermove"));a&&l>0&&!t&&e.splice(l+1,0,this.generateEventOfType(a,"mouseover")),r&&!n&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var d,m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3;if(!((d=e.events)!=null&&d.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let i=e.events,o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Kh(),zh)),Promise.resolve().then(()=>(_n(),On))]),c=`
229
229
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
230
230
  var dispatchFocus = ${l.toString()};
231
231
  var doDragPath = ${a.toString()};
232
232
  return doDragPath.apply(null, arguments);
233
233
  `;try{return(m=(await this.driver.executeCodeAsync(c,n,o)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset: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(_.flags.skipFileInputClicks.isEnabled()&&e.tagName==="INPUT"&&(e.elementSymbol.includes('type="file"')||e.elementSymbol.includes("type='file'")||e.elementSymbol.includes("type=file")))return{keep:!0,success:"skipped",reason:"Clicking on input type=file is disabled"};if(this.step.isDoubleClick){let d={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,d,o)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(_.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=`
234
234
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
235
- var dnd = ${jh.toString()};
235
+ var dnd = ${Vh.toString()};
236
236
  var eventData = arguments[0];
237
237
  var done = arguments[1];
238
238
  return dnd.call(null, eventData, done);
239
239
  `;return this.driver.executeCodeAsync(w,g,T)}let u=`
240
240
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
241
- var dnd = ${Fh.toString()};
241
+ var dnd = ${$h.toString()};
242
242
  var eventData = arguments[0];
243
243
  return dnd.call(null, eventData);
244
- `,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?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,zh=v(()=>{"use strict";pe();qn=class extends V{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:l}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(l,a)?{success:!0}:{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(l),actual:a}}}catch{return{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:l.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Kh,hE,Qo,Jh=v(()=>{"use strict";Kh=I(require("lodash"));pe();W();hE=P("evaluate-expression-step-action"),Qo=class extends V{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{hE.info("runner running incoming params evaluation");let i=t.incomingParams||{};Kh.isEmpty(i)&&(i=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let o=["context",...i.as.functionParameters],a=[t,...i.as.functionArguments],c=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,o.concat([c]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(i){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:i.toString()},success:!1}}}}});var Yh={};H(Yh,{setText:()=>yE});var yE,Xh=v(()=>{"use strict";yE=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(){Ze()},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 l(k){try{let N=document.createEvent("TextEvent");N.data=k.eventData.data;let $=1,K=k.eventData.locale||"en-US";return N.initTextEvent("textInput",!0,!0,window,k.eventData.data,$,K),N}catch{}}function c(k){return a(k)||l(k)}function d(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 m(k,N,$){try{let K=document.createEvent("KeyboardEvent");return K.initKeyEvent(k,!0,!0,null,Boolean($.ctrl),Boolean($.alt),Boolean($.shift),Boolean($.meta),N.key||"",0),K}catch{}}function u(k,N,$){try{let K=document.createEvent("Events");return K.initEvent(k,!0,!0),Object.assign(K,{altKey:Boolean($.alt),ctrlKey:Boolean($.ctrl),metaKey:Boolean($.meta),shiftKey:Boolean($.shift),keyCode:N.key||""}),K}catch{}}function f(k,N,$){return d(k,N,$)||m(k,N,$)||u(k,N,$)}function h(k){if(!i.has(k.event))return null;let N=k.eventData,$=N.modifiers||{},K=f(k.event,N,$);return Object.defineProperties(K,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(K,{_keyCode_:N.keyCode,_charCode_:N.charCode||0}),K}function g(k){return k.event==="textInput"?c(k):h(k)}function y(k,N){return(()=>{var K;return k.event==="textInput"&&!((K=N.quirks)!=null&&K.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 K=document.createEvent("HTMLEvents");K.initEvent("input",!0,!1),k.dispatchEvent(K),Object.defineProperty(k,"value",N)}function S(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 E(k,N,$){$?setTimeout(()=>{B(k)},w(N,$)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),S(k),Ze())}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 j(k,N){let $=k.firstChild,K;for(;$;){if($.nodeType===3){if(N.offset--<=0)return $}else if($.nodeType===1&&(K=j($,N),K))return K;$=$.nextSibling}return null}function R(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?$=j(k,{offset:N.nodeOffset}):$=k,$){let K=window.getSelection(),Pe=document.createRange();try{K.removeAllRanges(),Pe.setStart($,N.textOffset),Pe.setEnd($,N.textOffset),K.addRange(Pe)}catch{}}}}}function x(k,N){return k==="submit"&&Boolean(N.action)}function O(k,N,$){if(N.isFocusable&&N.isSelectable(k)&&k.type!=="submit")try{R(N.element,$.eventData.selection)}catch{}let K=D(k,N,$);if(!K)throw new Error("could not find element");x(k.type,K)?K.submit():K.dispatchEvent(k)}function B(k){let N,$=k.events[k.eventIndex],K=k.events[++k.eventIndex];try{N=g($)}catch(Pe){return St(`exception in get event in text step:${Pe.message}`)}if(y($,k))return E(k,$,K);if(N)try{O(N,k,$)}catch(Pe){return St(`exception in executeEvent in text step:${Pe.message}`)}else if(k.noEventExecuter)k.noEventExecuter(k,$);else return St(`cannot execute event ${$.event}`);E(k,$,K)}function G(k){let N=k.tagName;return N==="INPUT"||N==="TEXTAREA"}function z(k){return k.getAttribute?Boolean(k.getAttribute("contenteditable")==="true"):!1}function X(k,N){if(G(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 fe(){var N;let k=document.activeElement;for(;(N=k.shadowRoot)!=null&&N.activeElement;)k=k.shadowRoot.activeElement;return k}function Ze(k){let N={status:"done",result:k,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}function St(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=z(n.element),!k&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=k||n.isContentEditable,n.isSelectable=N=>N.type!=="keyup",n.noEventExecuter=X}catch(k){St(`exception in set text step:${k.message}`);return}let Br=fe();dispatchFocus(s.elementToFocusLocatedElement,Br),B(n)}});var Zo,Qh=v(()=>{"use strict";pe();F();Zo=class extends V{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(_e(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:l}=i.codeSnippets;if(o.isDraftEditor&&l)return this.driver.executeJS(l(o.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let c={eventType:t,events:e,quirks:r,locatedElement:o.locatedElement,isRoot:o.isRoot,elementToFocusLocatedElement:o.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(Xh(),Yh)),Promise.resolve().then(()=>(_n(),On))]),u=`
244
+ `,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?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,Yh=v(()=>{"use strict";pe();qn=class extends V{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:l}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(l,a)?{success:!0}:{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(l),actual:a}}}catch{return{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:l.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Xh,bE,Qo,Qh=v(()=>{"use strict";Xh=I(require("lodash"));pe();W();bE=P("evaluate-expression-step-action"),Qo=class extends V{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{bE.info("runner running incoming params evaluation");let i=t.incomingParams||{};Xh.isEmpty(i)&&(i=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let o=["context",...i.as.functionParameters],a=[t,...i.as.functionArguments],c=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,o.concat([c]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(i){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:i.toString()},success:!1}}}}});var Zh={};H(Zh,{setText:()=>TE});var TE,ey=v(()=>{"use strict";TE=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(){Ze()},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 l(k){try{let N=document.createEvent("TextEvent");N.data=k.eventData.data;let $=1,K=k.eventData.locale||"en-US";return N.initTextEvent("textInput",!0,!0,window,k.eventData.data,$,K),N}catch{}}function c(k){return a(k)||l(k)}function d(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 m(k,N,$){try{let K=document.createEvent("KeyboardEvent");return K.initKeyEvent(k,!0,!0,null,Boolean($.ctrl),Boolean($.alt),Boolean($.shift),Boolean($.meta),N.key||"",0),K}catch{}}function u(k,N,$){try{let K=document.createEvent("Events");return K.initEvent(k,!0,!0),Object.assign(K,{altKey:Boolean($.alt),ctrlKey:Boolean($.ctrl),metaKey:Boolean($.meta),shiftKey:Boolean($.shift),keyCode:N.key||""}),K}catch{}}function f(k,N,$){return d(k,N,$)||m(k,N,$)||u(k,N,$)}function h(k){if(!i.has(k.event))return null;let N=k.eventData,$=N.modifiers||{},K=f(k.event,N,$);return Object.defineProperties(K,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(K,{_keyCode_:N.keyCode,_charCode_:N.charCode||0}),K}function g(k){return k.event==="textInput"?c(k):h(k)}function y(k,N){return(()=>{var K;return k.event==="textInput"&&!((K=N.quirks)!=null&&K.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 K=document.createEvent("HTMLEvents");K.initEvent("input",!0,!1),k.dispatchEvent(K),Object.defineProperty(k,"value",N)}function S(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 E(k,N,$){$?setTimeout(()=>{B(k)},w(N,$)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),S(k),Ze())}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 j(k,N){let $=k.firstChild,K;for(;$;){if($.nodeType===3){if(N.offset--<=0)return $}else if($.nodeType===1&&(K=j($,N),K))return K;$=$.nextSibling}return null}function R(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?$=j(k,{offset:N.nodeOffset}):$=k,$){let K=window.getSelection(),Pe=document.createRange();try{K.removeAllRanges(),Pe.setStart($,N.textOffset),Pe.setEnd($,N.textOffset),K.addRange(Pe)}catch{}}}}}function x(k,N){return k==="submit"&&Boolean(N.action)}function O(k,N,$){if(N.isFocusable&&N.isSelectable(k)&&k.type!=="submit")try{R(N.element,$.eventData.selection)}catch{}let K=D(k,N,$);if(!K)throw new Error("could not find element");x(k.type,K)?K.submit():K.dispatchEvent(k)}function B(k){let N,$=k.events[k.eventIndex],K=k.events[++k.eventIndex];try{N=g($)}catch(Pe){return St(`exception in get event in text step:${Pe.message}`)}if(y($,k))return E(k,$,K);if(N)try{O(N,k,$)}catch(Pe){return St(`exception in executeEvent in text step:${Pe.message}`)}else if(k.noEventExecuter)k.noEventExecuter(k,$);else return St(`cannot execute event ${$.event}`);E(k,$,K)}function G(k){let N=k.tagName;return N==="INPUT"||N==="TEXTAREA"}function z(k){return k.getAttribute?Boolean(k.getAttribute("contenteditable")==="true"):!1}function X(k,N){if(G(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 fe(){var N;let k=document.activeElement;for(;(N=k.shadowRoot)!=null&&N.activeElement;)k=k.shadowRoot.activeElement;return k}function Ze(k){let N={status:"done",result:k,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}function St(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=z(n.element),!k&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=k||n.isContentEditable,n.isSelectable=N=>N.type!=="keyup",n.noEventExecuter=X}catch(k){St(`exception in set text step:${k.message}`);return}let Br=fe();dispatchFocus(s.elementToFocusLocatedElement,Br),B(n)}});var Zo,ty=v(()=>{"use strict";pe();F();Zo=class extends V{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(_e(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:l}=i.codeSnippets;if(o.isDraftEditor&&l)return this.driver.executeJS(l(o.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let c={eventType:t,events:e,quirks:r,locatedElement:o.locatedElement,isRoot:o.isRoot,elementToFocusLocatedElement:o.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(ey(),Zh)),Promise.resolve().then(()=>(_n(),On))]),u=`
245
245
  var getLocatedElement = ${i.codeSnippets.getLocatedElementCode};
246
246
  var dispatchFocus = ${m};
247
247
  var setText = ${d.toString()};
248
248
  var eventData = arguments[0];
249
249
  var done = arguments[1];
250
250
  return setText.call(null, eventData, done);
251
- `,f=await this.driver.executeCodeAsync(u,a,c);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(_e(t.seleniumElement),e[r]),r<e.length-1&&await ce(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(_e(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 Zh={};H(Zh,{runCode:()=>bE});var bE,ey=v(()=>{"use strict";bE=function(s,e){var d;function t(m,u){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let 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(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let i={},o={},a={},l=s.functionParams,c=s.transactionId;try{let m=r(s);m.push(i,o,a);let u=((d=s.function)==null?void 0:d.params)||l,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(c,{type:"promise"}),h.then(g=>{t(c,{status:"done",success:!0,result:{resultValue:g,exports:i,exportsTest:o,exportsGlobal:a}})},g=>{t(c,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:i,exportsTest:o,exportsGlobal:a}})})):t(c,{status:"done",success:!0,result:{resultValue:h,exports:i,exportsTest:o,exportsGlobal:a}})}catch(m){t(c,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:i,exportsTest:o,exportsGlobal:a}})}}});var ea,zn,ir,ta=v(()=>{"use strict";ea=I(require("lodash"));F();pe();W();ue();zn=P("base-js-step-action"),ir=class extends V{isExceedingMaxResultSize(t,r){var n;try{let i=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,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=>{ea.isObject(o)&&Pi(o,"seleniumElement",ea.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,l=async()=>{let c;try{c=await this.executeGetStatus(t)}catch(u){zn.warn("failed to get js status",{err:u}),c={value:'{ "status": "exception" }'}}let d;try{d=JSON.parse((c==null?void 0:c.value)||"{}")}catch{zn.warn("non object value",{selRes:c}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===i);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-o<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=o,await ce(o),l()):{success:!0})};return l()}async executeInAut(t){let r=_.flags.experimentalPreCodeCompilation.isEnabled(),n=_.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(t),o=i.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=i.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
251
+ `,f=await this.driver.executeCodeAsync(u,a,c);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(_e(t.seleniumElement),e[r]),r<e.length-1&&await ce(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(_e(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 ry={};H(ry,{runCode:()=>wE});var wE,sy=v(()=>{"use strict";wE=function(s,e){var d;function t(m,u){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let 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(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let i={},o={},a={},l=s.functionParams,c=s.transactionId;try{let m=r(s);m.push(i,o,a);let u=((d=s.function)==null?void 0:d.params)||l,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(c,{type:"promise"}),h.then(g=>{t(c,{status:"done",success:!0,result:{resultValue:g,exports:i,exportsTest:o,exportsGlobal:a}})},g=>{t(c,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:i,exportsTest:o,exportsGlobal:a}})})):t(c,{status:"done",success:!0,result:{resultValue:h,exports:i,exportsTest:o,exportsGlobal:a}})}catch(m){t(c,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:i,exportsTest:o,exportsGlobal:a}})}}});var ea,zn,ir,ta=v(()=>{"use strict";ea=I(require("lodash"));F();pe();W();ue();zn=P("base-js-step-action"),ir=class extends V{isExceedingMaxResultSize(t,r){var n;try{let i=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,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=>{ea.isObject(o)&&Pi(o,"seleniumElement",ea.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,l=async()=>{let c;try{c=await this.executeGetStatus(t)}catch(u){zn.warn("failed to get js status",{err:u}),c={value:'{ "status": "exception" }'}}let d;try{d=JSON.parse((c==null?void 0:c.value)||"{}")}catch{zn.warn("non object value",{selRes:c}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===i);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-o<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=o,await ce(o),l()):{success:!0})};return l()}async executeInAut(t){let r=_.flags.experimentalPreCodeCompilation.isEnabled(),n=_.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(t),o=i.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=i.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
252
252
  ${t.code}
253
253
  };`:`function(${m.join(",")}) {
254
254
  ${t.code}
255
- };`,i.function.params.pop()}let{codeSnippets:l}=this.sessionPlayerInit,{runCode:c}=await Promise.resolve().then(()=>(ey(),Zh)),d=`
255
+ };`,i.function.params.pop()}let{codeSnippets:l}=this.sessionPlayerInit,{runCode:c}=await Promise.resolve().then(()=>(sy(),ry)),d=`
256
256
  ${o?`var getLocatedElement = ${l.getLocatedElementCode};`:";"}
257
257
  var runCode = ${c.toString()};
258
258
  var eventData = arguments[0];
259
259
  var funcToRun = ${a};
260
260
  return runCode.call(null, eventData, funcToRun);
261
- `;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:l}=t;i.exports&&(n.data.exports=i.exports);let c={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}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),_.flags.useStepResultIdForStepTransactions.isEnabled()&&("stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:zn.warn("useStepResultIdForStepTransactions is enabled but 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 Wt,ty=v(()=>{"use strict";ta();Wt=class extends ir{isFailedResult(e){return e===!1}}});var vs,ry=v(()=>{"use strict";ta();vs=class extends ir{isFailedResult(e){return!e}}});var ra,sy=v(()=>{"use strict";pe();F();Ko();ra=class extends V{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(_e(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(Vn[t]),this.setWithValueApi(e)}}});var sa,ny=v(()=>{"use strict";pe();Ko();sa=class extends V{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(Vn[n])t.push(Vn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var iy={};H(iy,{selectOption:()=>TE});function TE(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 oy=v(()=>{"use strict"});var na,ay=v(()=>{"use strict";pe();F();ue();na=class extends V{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(_e(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>(oy(),iy)),c=_.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
261
+ `;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:l}=t;i.exports&&(n.data.exports=i.exports);let c={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}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),_.flags.useStepResultIdForStepTransactions.isEnabled()&&("stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:zn.warn("useStepResultIdForStepTransactions is enabled but 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 Wt,ny=v(()=>{"use strict";ta();Wt=class extends ir{isFailedResult(e){return e===!1}}});var vs,iy=v(()=>{"use strict";ta();vs=class extends ir{isFailedResult(e){return!e}}});var ra,oy=v(()=>{"use strict";pe();F();Ko();ra=class extends V{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(_e(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(Vn[t]),this.setWithValueApi(e)}}});var sa,ay=v(()=>{"use strict";pe();Ko();sa=class extends V{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(Vn[n])t.push(Vn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var cy={};H(cy,{selectOption:()=>vE});function vE(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 ly=v(()=>{"use strict"});var na,uy=v(()=>{"use strict";pe();F();ue();na=class extends V{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(_e(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>(ly(),cy)),c=_.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
262
262
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
263
263
  const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
264
264
  const selectOption = ${l.toString()};
265
265
  return selectOption.apply(null, arguments);
266
- `;return(f=(await this.driver.executeJS(d,r,c)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var ia,cy=v(()=>{"use strict";pe();ia=class extends V{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var wE,oa,ly=v(()=>{"use strict";pe();wE=(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(){}}),oa=class extends V{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,l=o/2,c=this.step.element.clickOffset;if(c&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:u}=c;this.sessionPlayerInit.utils.isWithinTargetRect(wE(o,i,0,0),m,u)&&(a=m,l=u)}let d={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(l)}};return await this.driver.hover(t,d),{success:!0}}}});var uy={};H(uy,{wheel:()=>vE});var vE,py=v(()=>{"use strict";vE=function(s,e){function r(a,l){function c(h,g,y){return y>h&&y<g}let d=a.pointerPosition||{},m=l.getBoundingClientRect(),u=d.originX&&c(m.left,m.left+m.width,d.originX)?d.originX:m.left+m.width/2,f=d.originY&&c(m.top,m.top+m.height,d.originY)?d.originY:m.top+m.height/2;return{x:u,y:f}}function n(a,l,c){let d=r(a,c),m=(l==null?void 0:l.modifiers)||{},u={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:d.x,clientY:d.y,bubbles:!0,cancelable:!0,ctrl:Boolean(m.ctrl),alt:Boolean(m.alt),shift:Boolean(m.shift),meta:Boolean(m.meta)};return new WheelEvent("wheel",u)}function i(a,l){if(a.length===0){e({state:"success"});return}if(!l)throw new Error("element not found");let c=a.shift(),d=n(c,s.eventData,l),m=a[0]?Math.min(a[0].timeStamp-c.timeStamp,200):200;l.dispatchEvent(d),setTimeout(()=>{i(a,l)},m)}let o=getLocatedElement(s.locatedElement);i(s.events,o)}});var aa,dy=v(()=>{"use strict";pe();aa=class extends V{async performAction(){var m;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:l}=await Promise.resolve().then(()=>(py(),uy)),c=`
266
+ `;return(f=(await this.driver.executeJS(d,r,c)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var ia,py=v(()=>{"use strict";pe();ia=class extends V{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var SE,oa,dy=v(()=>{"use strict";pe();SE=(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(){}}),oa=class extends V{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,l=o/2,c=this.step.element.clickOffset;if(c&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:u}=c;this.sessionPlayerInit.utils.isWithinTargetRect(SE(o,i,0,0),m,u)&&(a=m,l=u)}let d={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(l)}};return await this.driver.hover(t,d),{success:!0}}}});var my={};H(my,{wheel:()=>EE});var EE,fy=v(()=>{"use strict";EE=function(s,e){function r(a,l){function c(h,g,y){return y>h&&y<g}let d=a.pointerPosition||{},m=l.getBoundingClientRect(),u=d.originX&&c(m.left,m.left+m.width,d.originX)?d.originX:m.left+m.width/2,f=d.originY&&c(m.top,m.top+m.height,d.originY)?d.originY:m.top+m.height/2;return{x:u,y:f}}function n(a,l,c){let d=r(a,c),m=(l==null?void 0:l.modifiers)||{},u={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:d.x,clientY:d.y,bubbles:!0,cancelable:!0,ctrl:Boolean(m.ctrl),alt:Boolean(m.alt),shift:Boolean(m.shift),meta:Boolean(m.meta)};return new WheelEvent("wheel",u)}function i(a,l){if(a.length===0){e({state:"success"});return}if(!l)throw new Error("element not found");let c=a.shift(),d=n(c,s.eventData,l),m=a[0]?Math.min(a[0].timeStamp-c.timeStamp,200):200;l.dispatchEvent(d),setTimeout(()=>{i(a,l)},m)}let o=getLocatedElement(s.locatedElement);i(s.events,o)}});var aa,gy=v(()=>{"use strict";pe();aa=class extends V{async performAction(){var m;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:l}=await Promise.resolve().then(()=>(fy(),my)),c=`
267
267
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
268
268
  var wheel = ${l.toString()};
269
269
  var eventData = arguments[0];
270
270
  var done = arguments[1];
271
271
  return wheel.call(null, eventData, done);
272
- `;return{success:((m=(await this.driver.executeCodeAsync(c,a,o)).value)==null?void 0:m.state)==="success"}}}});var my={};H(my,{downloadFileAndFireDropEvent:()=>SE});var SE,fy=v(()=>{"use strict";SE=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let o=-1,a=0,l=[],c={endWithCallback:void 0,waitOn(){let d=++o;return function(m){d in l||(l[d]=m,a++,e.length===a&&c.endWithCallback(l))}},endWith(d){c.endWithCallback=d}};return c}function n(o,a,l){let c=new XMLHttpRequest;c.open("GET",o),c.responseType="blob",c.onload=function(){if(this.status>=200&&this.status<300)l({blob:c.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},c.onerror=function(){throw new Error("Failed to load blob")},c.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 EE,ca,gy=v(()=>{"use strict";pe();W();ue();EE=P("drop-file-step-action"),ca=class extends V{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,i=this.getTarget(),o=_.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,o,EE),{downloadFileAndFireDropEvent:l}=await Promise.resolve().then(()=>(fy(),my)),c=`
272
+ `;return{success:((m=(await this.driver.executeCodeAsync(c,a,o)).value)==null?void 0:m.state)==="success"}}}});var hy={};H(hy,{downloadFileAndFireDropEvent:()=>IE});var IE,yy=v(()=>{"use strict";IE=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let o=-1,a=0,l=[],c={endWithCallback:void 0,waitOn(){let d=++o;return function(m){d in l||(l[d]=m,a++,e.length===a&&c.endWithCallback(l))}},endWith(d){c.endWithCallback=d}};return c}function n(o,a,l){let c=new XMLHttpRequest;c.open("GET",o),c.responseType="blob",c.onload=function(){if(this.status>=200&&this.status<300)l({blob:c.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},c.onerror=function(){throw new Error("Failed to load blob")},c.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 RE,ca,by=v(()=>{"use strict";pe();W();ue();RE=P("drop-file-step-action"),ca=class extends V{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,i=this.getTarget(),o=_.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,o,RE),{downloadFileAndFireDropEvent:l}=await Promise.resolve().then(()=>(yy(),hy)),c=`
273
273
  const getLocatedElement = ${e.getLocatedElementCode};
274
274
  const createDropEvent = ${e.createDropEvent.toString()};
275
275
  const downloadFileAndFireDropEvent = ${l.toString()};
276
276
  return downloadFileAndFireDropEvent.apply(null, arguments)
277
- `;return await this.driver.executeJS(c,i.locatedElement,a)}}});function by(s={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
277
+ `;return await this.driver.executeJS(c,i.locatedElement,a)}}});function vy(s={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
278
278
  var input = getLocatedElement(locatedElement);
279
279
  if(input) {
280
280
  function parents(element, _elements) {
@@ -316,7 +316,7 @@ Please make sure the CLI has stable access to the internet. ${Ec()?"(Internal: n
316
316
  input.removeAttribute("disabled");
317
317
  input.focus();
318
318
  }
319
- }`}async function RE(s,e){let t=null;try{t=(await vc(s)).body}catch(n){if(IE.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=`${hy.tmpdir()}/${e}`;return await yy.promises.writeFile(r,t),r}function xE(s){return se(s,e=>RE(e.url,e.name))}function AE(s,e){return e(s)}async function Ty(s,e){let t=await xE(s),r=await se(t,n=>AE(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var hy,yy,IE,wy=v(()=>{"use strict";hy=I(require("os"));Ve();yy=require("fs");F();W();IE=P("input-file-utils")});function PE(){return`async function downloadAndUpload(locatedElement, fileUrls) {
319
+ }`}async function AE(s,e){let t=null;try{t=(await vc(s)).body}catch(n){if(xE.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=`${Ty.tmpdir()}/${e}`;return await wy.promises.writeFile(r,t),r}function CE(s){return se(s,e=>AE(e.url,e.name))}function PE(s,e){return e(s)}async function Sy(s,e){let t=await CE(s),r=await se(t,n=>PE(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var Ty,wy,xE,Ey=v(()=>{"use strict";Ty=I(require("os"));Ve();wy=require("fs");F();W();xE=P("input-file-utils")});function OE(){return`async function downloadAndUpload(locatedElement, fileUrls) {
320
320
  const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
321
321
  const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
322
322
  const attachTo = document.body || document.documentElement;
@@ -393,31 +393,31 @@ Please make sure the CLI has stable access to the internet. ${Ec()?"(Internal: n
393
393
  element.dispatchEvent(new Event("change", { bubbles: true }));
394
394
  }
395
395
  element.removeEventListener("change", changeFiredHandler, true);
396
- }`}var la,ua,vy=v(()=>{"use strict";wy();pe();W();F();ue();la=P("input-file-step-action"),ua=class extends V{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){la.info("workaround - stepaction - move element to visible position");let n=`
396
+ }`}var la,ua,Iy=v(()=>{"use strict";Ey();pe();W();F();ue();la=P("input-file-step-action"),ua=class extends V{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){la.info("workaround - stepaction - move element to visible position");let n=`
397
397
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
398
- var getVisibleElement = ${by(r)};
398
+ var getVisibleElement = ${vy(r)};
399
399
  return getVisibleElement.apply(null, arguments);
400
400
  `;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw la.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let i="The element is not editable",o="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(i)||f.startsWith(o)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw la.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(_e(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=_.flags.overrideAzureStorageUrl.isEnabled(),n=_.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:l,driver:c}=this,d=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,l.testimServicesApi,r,la);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await Mt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
401
401
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
402
- const downloadAndUploadFile = ${PE()};
403
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Ty(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var pa,da,Sy=v(()=>{"use strict";pa=require("url");pe();da=class extends V{async updateBaseUrl(e){let t=new pa.URL(e),r=new pa.URL(this.context.recordedBaseUrl),n=new pa.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var ma,Ey=v(()=>{"use strict";pe();F();ma=class extends V{async performAction(){await ce(this.step.durationMS||0)}}});var fa,Iy=v(()=>{"use strict";pe();fa=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Kn,Ry=v(()=>{"use strict";pe();Kn=class extends V{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 ga,xy=v(()=>{"use strict";pe();ga=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Ay,Fu,Bu,Cy=v(()=>{"use strict";Ay=I(require("@applitools/spec-driver-webdriverio"));mi();we();Fu=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=pd["@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:Ay.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}},Bu=new Fu});var ky,Py,Jn,Oy=v(()=>{"use strict";ky=I(require("lodash"));pe();W();Cy();Py=P("pixel-validation-step-action"),Jn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Bu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};ky.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),Py.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){Py.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Bu.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ss,ju=v(()=>{"use strict";hs();Y();ta();Ss=class extends ir{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await gs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var or,_y=v(()=>{"use strict";ju();or=class extends Ss{isFailedResult(e){return e===!1}}});var ha,Ly=v(()=>{"use strict";ju();ha=class extends Ss{isFailedResult(e){return!e}}});var ya,Dy=v(()=>{"use strict";hs();pe();Y();ya=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await fs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Lr,Ny=v(()=>{"use strict";pe();Lr=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,My=v(()=>{"use strict";pe();be=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ba,Uy=v(()=>{"use strict";pe();ba=class extends V{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 Ta,Fy=v(()=>{"use strict";pe();Ta=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function kE(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function wa(s,e){kE(OE,e),e.registerLocateStepActionUtils(Gn.getUtils(s))}var OE,$u=v(()=>{"use strict";Dh();Uh();qh();zh();Jh();Qh();ty();ry();sy();ny();ay();cy();ly();dy();gy();vy();Sy();Ey();Iy();Ry();xy();Oy();_y();Ly();Dy();Ny();My();Uy();Fy();OE={locate:Gn,scroll:Yo,mouse:Xo,submit:ia,text:Zo,"special-key":ra,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":vs,"skip-code-step":vs,"element-code-step":vs,"evaluate-expression":Qo,"text-validation":qn,"wait-for-text-validation":qn,"select-option":na,"drop-file":ca,"input-file":ua,hover:oa,navigation:da,wheel:aa,sleep:ma,refresh:fa,"keyboard-shortcut-step":sa,"api-validation":Kn,"api-action":Kn,"api-code-step":Wt,"extract-text":ga,"simple-ui-verification":Jn,"wait-for-simple-ui-verification":Jn,"cli-validation-download-file":Lr,"cli-wait-for-download-file":Lr,"network-validation-step":Lr,"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":ha,"node-package":ya,"email-code-step":Wt,"cli-email-code-step":or,"sfdc-internal-test-step":Ta,"sfdc-recorded-step":ba,"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":Lr,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var By,_E,Es,Wu=v(()=>{"use strict";By=["simple-ui-verification","wait-for-simple-ui-verification"],_E=[...By,"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"],Es=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=_E.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 By.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 $y={};H($y,{SeleniumTestPlayer:()=>Yn});var jy,LE,Yn,Vu=v(()=>{"use strict";F();jy=require("@applitools/eyes-sdk-core");Ln();Y();W();_u();Ph();Mu();Ko();_h();Uu();we();$u();Wu();LE=P("SeleniumTestPlayer"),Yn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(Jo());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Z();this.driver=n??new Ar;let d=new zo(this.driver);this.stepActionFactory=new c(d),wa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ho(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Oh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:qo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:jy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){LE.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Hu={};H(Hu,{WorkerSelenium:()=>Gu});function NE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var va,DE,Gu,qu=v(()=>{"use strict";F();je();Wn();W();Pt();Po();ie();ku();Y();Vu();we();at();va=P("worker-selenium"),DE=1e9,Gu=class extends Ot{initPlayer(t){return new Yn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){M("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ts(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,DE),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(va.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Ki(),initializedFromCache:Ji()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),NE(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await Mn(this.options))[this.testId]);let d=async()=>le(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof oe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(va.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=o.maxKeepAliveGap();f>=3e4&&(va.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw va.error("failed to run test once",{err:u}),u}}}});var Wy,Vy,Ge,ME,UE,zu,vt,Sa=v(()=>{"use strict";Wy=I(require("ora")),Vy=require("jimp");de();Ve();ge();W();ie();we();ue();Ge=P("mobile-grid-service"),ME="https://tdc.tricentis-cloud.com",UE="https://ui.headspin.io",zu=class{constructor(){this.gridsAppIdGetter={[L.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[L.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[L.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[L.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[L.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[L.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===L.TESTIM_HEADSPIN?`${r||oc}/${cc}/devices`:t===L.TESTIM_TDC?`${r||ac}/${cc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:i})}catch(o){throw Ge.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw Ge.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Gs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===L.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===L.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([L.BROWSERSTACK,L.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,l,c;if(t===L.TESTIM_HEADSPIN||t===L.TESTIM_TDC){let d=await Qn({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=Z();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Ir(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),Ge.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await Vy.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/c.width,width:u,height:f}}catch(o){return Ge.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Us}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?UE:ME}/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:l}=t,c=await this.getTmaDeviceDetails(l,e);return await Ir(a,n,i,o,"RUNNING",{device:c}),Ge.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:c}),c}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(_.flags.allowFixingAppIdStructure.isEnabled()&&(Ge.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ju({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 Xn({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/(xd*60))+1)*60*1e3,Math.max(Rd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[L.BROWSERSTACK]:{name:"Browserstack"},[L.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[L.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Wy.default)(`uploading app to ${a} please wait..`).start();try{Ge.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Ku({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){Ge.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else Ge.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===L.BROWSERSTACK||f===L.TESTIM_TVC||f===L.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(Ge.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&Ge.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Us}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${lc}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?oc:ac}/${lc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Ad}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&Ge.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===L.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await Tc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},vt=new zu});function Gy({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"&&!FE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function BE({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==L.TESTIM_TDC&&e.type!==L.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function jE(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 $E(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&_.flags.enableBatchHeadSpin.isEnabled(),d=o&&(_.flags.enableBatchTDC.isEnabled()||_.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=_.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,..._.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:jE(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Ea(s){return"id"in s?s.id:s.packageName}function WE(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function VE({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=WE(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":Ea(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":Ea(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Nr({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`]:Ea(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`]:Ea(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Hy({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let l=$E(o.type,i,n);return VE({projectType:s,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Ra({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function xa({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===L.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?uc:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":uc:".*")}function GE(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 HE(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ia(s,Is)}}function qy(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 qE(s){return qy(s,e=>e.startsWith("browserstack."),"browserstack.")}function zE(s){return qy(s,e=>!e.startsWith("browserstack."))}function zy(s){return!s||!Ky(s)?"2.0.0":s}function Ky(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Jy({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=Ky(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ia(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}async function KE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:l}){let{osVersion:c,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=GE(i,s),h=await Qn({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:S})=>{var E;return((E=m.staticAllocation)==null?void 0:E.deviceUdid)===S}),y=(g==null?void 0:g.osVersion)??Ra({osVersion:c,mobileConfig:m}),T=(g==null?void 0:g.name)??xa({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),w=qe(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,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:l})}function JE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=_.flags.enableAppium2pCloudy.isEnabled(),g=Ra({osVersion:l,mobileConfig:d}),y=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),w={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...w,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Cd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=HE(b)),t="",Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Is}})}function YE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Ra({osVersion:l,mobileConfig:d}),f=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Dr.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Jy({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:zy(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ia(h,Is),"sauce:options":{...T,...w,...(0,Dr.omit)(g,"appiumVersion")}};return Nr({projectType:s,sessionCaps:b,appiumPrefix:Is,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 Nr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function XE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Ra({osVersion:l,mobileConfig:d}),f=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=qE(n.browserstack),g=(0,Dr.omit)(zE(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:w}=n.browserstack||{},b=_.flags.enableAppium2BrowserStack.isEnabled();if(b||Jy({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":zy(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},A={"appium:platformVersion":u,"appium:deviceName":f,...Ia(g,Is),"bstack:options":{...E,...(0,Dr.omit)(h,"appiumVersion")}};return Nr({projectType:s,sessionCaps:A,appiumPrefix:Is,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let S={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:w||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ia(h,"browserstack.")};return Nr({projectType:s,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}async function QE(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Hy(s);if(L.TESTIM_TVC===s.gridInfo.type)return await KE(s);if(L.P_CLOUDY===s.gridInfo.type)return JE(s);if(L.SAUCELABS===s.gridInfo.type)return YE(s);if(L.BROWSERSTACK===s.gridInfo.type)return XE(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function ZE(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}async function Yy(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}`);Gy({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=await QE(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=ZE(r,i==null?void 0:i.mobile);if(!(0,Dr.isEmpty)(T)){let w=Object.entries(T).map(([b,S])=>S.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=w}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=_.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Yu.default)("2m"),f=(0,Yu.default)("12m"),h=mr(_.flags.appiumConnectionRetryCount.getValue(),m),g=mr(_.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function Xy(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Gy({nativeAppMetadata:r,appPath:i,gridInfo:t}),BE({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=Hy({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Qy(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Nr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function Zy(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 Yu,Dr,Is,FE,Xu=v(()=>{"use strict";Yu=I(require("ms"));ue();ie();Sa();Dr=require("lodash");F();de();ge();Is="appium:",FE=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var Aa,tb=v(()=>{"use strict";Aa=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Ca,rb=v(()=>{"use strict";F();Ca=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Xs;this.getLinksFromUnescapeHTML=Qs}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 Qu,Pa,sb=v(()=>{"use strict";W();Qu=P("mobile-frame-locator-mock"),Pa=class{foundFrameCallback(){return Qu.info("foundFrameCallback-mock invoked"),{}}locate(){return Qu.info("locate-mock invoked"),{}}async findFrame(){return Qu.info("findFrame-mock invoked"),{}}}});var eI,ib,nb,Rs,Zu=v(()=>{"use strict";eI=I(require("webdriverio")),ib=require("@applitools/eyes-sdk-core");tb();Mu();W();rb();Uu();we();$u();sb();Wu();nb=P("appium-test-player"),Rs=class{constructor(e,t,r,n=eI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Z(),m=new Ca(this.driver);this.stepActionFactory=new c(m),wa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(Jo()),this.sessionPlayer=new a(e,{tabService:new Aa,cookieUtils:void 0,FrameLocator:Pa,portSelector:qo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:ib.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),nb.info("appium session deleted",{...i}))}catch(o){nb.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 tI(s){return await Te(`${s}/api/status`)}async function ob(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function ab(s){if((await tI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var cb=v(()=>{"use strict";Ve()});var lb={};H(lb,{WorkerLocalTma:()=>sp});var Mr,ep,tp,rp,sp,ub=v(()=>{"use strict";Ve();Xu();Wn();F();W();Pt();Zu();we();cb();Sa();Mr=P("worker-appium"),ep=class extends Error{},tp=class extends Error{},rp=class extends Error{},sp=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Rs(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:l}=this.options;await ab(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:A}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:w,version:b},S]=await Promise.all([this.getAppStateFromDevice(o,a,T),ob(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Mr.info("device status and app state",{deviceStatus:S,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),Mr.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=Qy({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),j={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:j,executionId:this.executionId,testResultId:this.testResultId});let R=await this.requestNewAppiumSessionFromTma(o,j,g);this.sessionData=R;let x=await m.attach({sessionId:R.sessionId,capabilities:D,options:{capabilities:D}});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:x.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:x.capabilities})}catch(A){throw Mr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new rp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await Te(o)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Mt(n);await Vs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new tp(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new ep(`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},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var db={};H(db,{WorkerAppium:()=>np});var pb,Ur,np,mb=v(()=>{"use strict";F();Xu();pb=require("linkedom");Wn();W();Pt();Zu();we();Sa();ie();os();Ur=P("worker-appium"),np=class extends Ot{initPlayer(t){return new Rs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==L.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:l}=n,c=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),d=o==="android"?t.androidActivityWait:null,m=t.nativeAppMetadata;if(!m)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:o,nativeAppMetadata:m,appPath:c,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(i,this.options.deviceUdid),h=await Xy(f)):h=await Yy({...f,shouldRunInEnhancedMode:a}),Ur.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:Zy(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await l.remote(h),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Ur.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Ur.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){Ur.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"&&Lf(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){Ur.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:S}=await vt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${S}`}else d=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,pb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Ur.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(),c)}catch(y){throw Ur.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:runner-v4.146.0"}}});var ka,fb=v(()=>{"use strict";F();Ln();Y();ka=class{constructor(e){this.id=e;this.driver=new Ar}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var gb,Oa,hb=v(()=>{"use strict";gb=I(require("ws"));F();Oa=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new gb.default(this._cdpUrl,{timeout:e}),r=Kt(i=>{t.once("open",i)}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var La,ip,_a,yb=v(()=>{"use strict";F();La=I(require("chrome-launcher"));eu();hb();En();ip=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Oa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Ro({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...La.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await La.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 gr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),as(()=>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}},_a=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new ip(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var op={};H(op,{WorkerExtension:()=>Zn});function rI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function bb(s){return rI(s)?s:new Error(s)}var dt,Zn,Da=v(()=>{"use strict";je();Y();Wn();F();W();Pt();ie();fb();yb();at();dt=P("worker-ext"),Zn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new ka(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw dt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Ki(),initializedFromCache:Ji(),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;M("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(d.cdpTestRunner),m,Me.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))throw u;return dt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw dt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(M("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw dt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Me.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;dt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),dt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=qs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=le(e.onCompleted(),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG),w=await gc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(E){dt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(dt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(dt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw dt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),bb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw dt.warn("failed to start url",{err:h}),bb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await c()}catch(d){throw dt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var cp={};H(cp,{WorkerExtensionSingleBrowser:()=>ap});var sI,nI,ap,lp=v(()=>{"use strict";je();F();W();xu();Pt();Da();sI=P("base-worker"),nI=500,ap=class extends Zn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await jn(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,i){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(sI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let i=this.handleQuarantine(t);if(i)return i;M("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ce(nI)}}});var up,Na,Tb=v(()=>{"use strict";Ln();de();je();hl();at();au();Y();W();ie();dh();Mo();up=P("worker-manager"),Na=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(qu(),Hu))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(ub(),lb))).WorkerLocalTma:(await Promise.resolve().then(()=>(mb(),db))).WorkerAppium;default:return Dn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(lp(),cp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Da(),op))).WorkerExtension}else switch(r){case(Or.find(n=>n===r)&&Dn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(lp(),cp))).WorkerExtensionSingleBrowser;case Or.find(n=>n===r):return(await Promise.resolve().then(()=>(Da(),op))).WorkerExtension;case Bn.find(n=>n===r):return(await Promise.resolve().then(()=>(qu(),Hu))).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 M("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var fe,Ze,St,Br,k,N,$,K;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new No(r,n,e,i,o,t),this.combinedTestResults={};let T=((fe=i.company)==null?void 0:fe.ucid)||"",w=(Ze=i.company)==null?void 0:Ze.companyId,b=(St=i.company)==null?void 0:St.name,S=i.source||"cli",E=i.user,A=(Br=i.company)==null?void 0:Br.planType,D=(k=i.company)==null?void 0:k.isStartUp,j=(N=i.projectData)==null?void 0:N.name,R=($=i.projectData)==null?void 0:$.type,x=i.lightweightMode,O=(K=i.gridData)==null?void 0:K.type,B=(Pe,Et,ve,Qa,ni,Za)=>(d++,yf({executionId:r,projectId:g,testId:Et,resultId:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,isStartUp:D,projectType:R,appSource:Za,gridType:O}),t.testStartAndReport(Pe,r,ve,Qa,ni)),G=async(Pe,Et,ve,Qa,ni,Za)=>{var id,od,ad;d--;let et={...(x==null?void 0:x.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||((id=i.gridData)==null?void 0:id.name),et.gridType=(od=i.gridData)==null?void 0:od.type,et.gridProvider=(ad=i.gridData)==null?void 0:ad.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(Pe,ve,r,Qa,ni,et).catch(UT=>up.error("testEndAndReport threw an error",{err:UT})),ni)return;this.combinedTestResults[ve.resultId]=ve,bf({executionId:r,projectId:g,testId:Et,resultId:ve.resultId,result:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,logger:up,isStartUp:D,projectType:R,appSource:Za}),l&&!ve.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},z=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},X=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...wr(),refreshToken:qi(),authData:wr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,B,G,X,z)});try{let u=await At(),f=await zi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw up.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var pp,ae,wb=v(()=>{"use strict";pp=class{static colorString(e,t){return`${e}${t}${pp.Reset}`}},ae=pp;ae.Reset="\x1B[0m",ae.Bright="\x1B[1m",ae.Dim="\x1B[2m",ae.Underscore="\x1B[4m",ae.Blink="\x1B[5m",ae.Reverse="\x1B[7m",ae.Hidden="\x1B[8m",ae.FgBlack="\x1B[30m",ae.FgRed="\x1B[31m",ae.FgGreen="\x1B[32m",ae.FgYellow="\x1B[33m",ae.FgBlue="\x1B[34m",ae.FgMagenta="\x1B[35m",ae.FgCyan="\x1B[36m",ae.FgWhite="\x1B[37m",ae.FgGray="\x1B[90m",ae.BgBlack="\x1B[40m",ae.BgRed="\x1B[41m",ae.BgGreen="\x1B[42m",ae.BgYellow="\x1B[43m",ae.BgBlue="\x1B[44m",ae.BgMagenta="\x1B[45m",ae.BgCyan="\x1B[46m",ae.BgWhite="\x1B[47m",ae.BgGray="\x1B[100m"});var ei,vb,Ma,dp,mp,Fr,fp=v(()=>{"use strict";ei=I(require("lodash"));F();W();de();ie();je();ts();gl();hl();ge();ue();Pt();ng();Y();Tb();Mo();vb=require("uuid");wb();({CLI_MODE:Ma}=Ut),dp=P("test-plan-runner"),mp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return mp._id}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Na(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,g,y);Object.assign(c,T)},u=async()=>{let g=hi||i.parallel,y=!1;M("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);M("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};Tf({executionId:o,projectId:i.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),c}catch(g){if(dp.error("error running test plan",{err:g}),g instanceof qt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Ma.SELENIUM){let[{getSessionPlayer:S},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(we(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=S();await A.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await bp(i.project),ei.default.isEmpty(g)||!o))return;let{runKey:S,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:S}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,S,E;let c=re(),d=n.project;jd(c),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new bo(m,n,o,a),f=ei.default.chain(m).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);M("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),M("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return M("before executionEnd"),await u.executionEnd(c),M("after executionEnd"),{results:w,executionId:c,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(ae.colorString(ae.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await gp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await hp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){dp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return ei.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};_.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async d=>{let m=await ti(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await se(e.testPlan,async d=>{let m=await ti(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await ti(o,e.testPlan,e.testPlanIds,t,e.intersections);let l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Ma.APPIUM&&await Iu(e,r(c)),await se(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await sf(e,d);let f=u.overrideExecutionName||d.name;return await se(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Eu(n[m][E])})),w=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,A)=>Object.assign(E,A),{}),b=Eu(w);Object.assign(i,w);let S=b?T[0].executionId:T.find(E=>!E.status).executionId;return await yp(o,m,{success:b,executions:T,executionId:S}),y})})}async runAnonymousTestPlan(e,t){var l;dp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await fh(e,t);if(M("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.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;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Ma.APPIUM&&(a=await Xn({appId:e.appId,projectId:e.project})),await se(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Ma.APPIUM&&await Iu(e,c),M("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return M("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=fn(),r=[];await this.reportTestRunnerStarted(e.project,e),Ks(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ei.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Fr=mp;Fr._id=(0,vb.v4)()});var Re={};H(Re,{addTestRetry:()=>Kl,clearTestResult:()=>vu,deleteCloudflareTunnel:()=>xp,fetchLambdatestConfig:()=>Yl,fixGridAppIDStructure:()=>Ju,forceUpdateCloudflareTunnelRoutes:()=>Rp,getAllGrids:()=>fl,getAppDetails:()=>Xn,getApplitoolsIntegrationData:()=>bp,getBrowserStackSessionMetaData:()=>fI,getCloudflareTunnel:()=>Ip,getEditorUrl:()=>pI,getGridSlot:()=>ml,getHybridGridProvider:()=>dl,getLabFeaturesByProjectId:()=>cu,getMobileDevicesFromGrid:()=>Qn,getRealData:()=>$l,getS3Artifact:()=>xn,getS3ArtifactText:()=>jl,getSuiteTestList:()=>Ru,getTestPlan:()=>uI,getTestPlanTestList:()=>ti,getTestResults:()=>kr,getUsageForCurrentBillingPeriod:()=>Sp,initializeUserWithAuth:()=>Ep,isTestResultCompleted:()=>wu,keepAliveCompanySlots:()=>Fl,keepAliveGrid:()=>ul,loadSfdcCredential:()=>vp,loadTest:()=>Un,releaseCompanySlot:()=>Ml,releaseGridSlot:()=>pl,reportExecutionFinished:()=>To,reportExecutionStarted:()=>zl,reportRunnerFinished:()=>hp,reportRunnerStarted:()=>gp,requestCompanySlot:()=>Nl,saveRemoteStep:()=>uu,saveTestPlanResult:()=>yp,updateCompanySlot:()=>Ul,updateExecutionTests:()=>ql,updateRemoteRunFailure:()=>Ap,updateTestDataArtifact:()=>wo,updateTestResult:()=>jo,updateTestStatus:()=>Ir,uploadAppToGrid:()=>Ku,uploadRunDataArtifact:()=>Su,validateUserAccessKey:()=>cl});async function xs(){let s=await At();if(!s)throw new Error("Failed to get token from server");return{[_c]:Fr.id,Authorization:`Bearer ${s}`}}async function Ee({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await xs(),o={...t,...i};return We({url:`${he}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function cI(s,e,t,r={},n=void 0){let i=await xs(),o={...r,...i};return await Vs(`${he}${s||""}`,e,t,o,n)}async function ri(s,e){let t=await xs();return await wc(`${he}${s||""}`,e,t)}async function Eb(s,e){let t=await xs();return await Ws(`${he}${s||""}`,e,t)}async function lI(s,e){let t=await xs();return await Gs(`${he}${s||""}`,e||void 0,t)}async function Ae(s,e,t,r){let n=await xs();return await Te(`${he}${s||""}`,e||void 0,n,r,t)}function xn(s,e){return(0,ee.default)(()=>Ae(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function jl(s){return(0,ee.default)(()=>lI(`/storage${s}`))}async function gp(s,e){return await Ee({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function hp(s){return await Eb("/test-runner",{projectId:s})}async function uI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>Ae("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function vp({branch:s,projectId:e}){let t=await(0,ee.default)(()=>Ae(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function Un({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>Ae(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function yp(s,e,t){return(0,ee.default)(()=>Ee({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Ir(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>ri("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:iI,...i}),{retries:o,factor:1})}function ql(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>ri("/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 zl({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Zi(),ff));return Ee({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function To(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>ri("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function ti(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Ru({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,ee.default)(()=>Ee({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:te,factor:1})}async function Xn({appId:s,projectId:e}){try{return await(0,ee.default)(()=>Ae(`/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 Sp(s){try{return await(0,ee.default)(()=>Ae(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){_t.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function wu(s,e,t){return(0,ee.default)(()=>Ae(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function kr(s,e,t,r){return(0,ee.default)(()=>Ae(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function ul(s,e){return Ee({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function pl(s,e,t,r,n){return Ee({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function dl(s){return Ee({url:"/grid/hybrid/provider",body:s})}function ml(s){return(0,ee.default)(()=>Ae("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Ep({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d}){var m,u;try{return await(0,ee.default)(()=>We({url:`${he}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d},timeout:6e4}),{retries:te,factor:1})}catch(f){if(_t.error("error initializing info from server",f),(m=f.message)!=null&&m.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(Tp.default[y](Tp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{_t.error("Error parsing error message from server",f)}throw f}}async function pI(){if(Ns)return{editorUrl:Ns};try{return await(0,ee.default)(()=>Ae("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return _t.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function fl(s){return(0,ee.default)(()=>Ae("/grid",{companyId:s}),{retries:te,factor:1})}function $l(s,e,t){return(0,ee.default)(()=>Ae(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function jo(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function vu(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function uu(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function dI(s){return s.startsWith("/")?s:`/${s}`}function mI(s,e,t){let r=dI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Ib(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,l=`${e}/${t}/${a}`,c=mI(l,aI,s),d=Buffer.from(Sb.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,ee.default)(()=>cI(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),c}function Kl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Ee({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 bp(s){try{return await Ae(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return _t.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Ip(s,e){try{return await ri("/tunnel",{companyId:s,routes:e})}catch(t){return _t.warn("could'nt get tunnel.",{err:t}),{}}}async function Rp(s,e){try{return await Ee({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}async function xp(s,e){try{return await Eb(`/tunnel/${e}`,{companyId:s})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}function Ap(s){return We({url:`${he}/result/remoteRunFailure`,body:s})}async function Qn({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${oI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>Ae(i,{projectId:s}),{retries:te,factor:1})}catch(o){return _t.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function Ku({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Ee({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function Ju(s){return(0,ee.default)(()=>Ee({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Nl(s,e){return(0,ee.default)(()=>Ee({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Ml(s,e,t){return(0,ee.default)(()=>Ee({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Ul(s,e,t){return(0,ee.default)(()=>ri("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Fl(s,e,t){return Ee({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function fI(s,e){return await Te(`${Us}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function cl(s){try{return await Ae("/v2/project/validateUserAccessKey",s),!0}catch(e){return _t.error("error validating user access key",{error:e}),!1}}var Tp,ar,Sb,ee,wp,iI,_t,te,oI,aI,Yl,cu,Su,wo,ge=v(()=>{"use strict";Tp=I(require("chalk")),ar=I(require("lodash")),Sb=I(require("pako"));F();de();ie();Ve();at();ee=I(require("p-retry")),wp=I(require("object-hash"));Y();W();fp();iI=tt(),_t=P("testim service api"),te=3,oI="/grid",aI="test-result-artifacts";Yl=async()=>(0,ee.default)(()=>Ae("/grid/lt/config"),{retries:te,factor:1}),cu=async s=>(0,ee.default)(()=>Ae(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Su=ar.memoize(async(s,e,t,r)=>{if(!ar.isEmpty(r))return await Ib(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,wp.default)(r)}:${e}:${t}`),wo=ar.memoize(async(s,e,t,r,n)=>!r||ar.isEmpty(r)?void 0:await Ib(s,e,t,JSON.stringify((()=>{let o=ar.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(c=>{o[c]&&Object.assign(o,{[c]:Pc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,wp.default)(r)}:${e}:${t}`)});async function Rb(){let s=await Promise.any(gI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var gI,xb=v(()=>{"use strict";Ve();gI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});function Ua(){return tt()}var Cp=v(()=>{"use strict";F()});function bI(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(we(),He(tr)).getSessionPlayer()}catch{}})}function TI(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(Pp.default[i](Pp.default[n](r.text)))})}async function si(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?yI:hI,f=Ua(),h=xc(),g=await Lm(),y=null;if(_.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Rb()}catch(b){Ab.error("failed to get public ip",b)}let T=!0;M("before initializeUserWithAuth");let w=await Bt(async()=>(bI(a),T=!1,await Ep({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:y,gridId:l,grid:c,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:y})();return TI(w),s.publicIps=[w.clientPublicIp],M("after initializeUserWithAuth"),y&&w.clientPublicIp&&w.clientPublicIp!==y&&(Ab.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:w.clientPublicIp}),s.publicIps.push(y)),Xm(w.authData,{projectId:e,token:t,userAccessKey:r,publicIp:w.clientPublicIp,initializedFromCache:T}),w}var Pp,Ab,hI,yI,Cb=v(()=>{"use strict";Pp=I(require("chalk"));je();ge();Yt();at();xb();ie();W();ue();Cp();F();Zr();Ab=P("initializeUserWithAuth"),hI=1e3*60*5,yI=1e3*60*60*10});async function Ob(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Hi():s.chromeBinaryLocation,e=tn({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!==q.EXTENSION&&await br(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await Qc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Xc(s.installCustomExtension,n)}return await e,t}async function _b(s){var o;wI.info("prepare MockNetwork",{location:s});let e=await Ic(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Pb*1e6)throw new Error(`${kp} exceeded ${Pb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${kp} cannot be parsed.${Fa.EOL}${a}`)}let n=new kb.default;if(!n.validate(Bc,r)){let a=(o=n.errors)==null?void 0:o.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Fa.EOL);throw new Error(`${kp} is malformed.${Fa.EOL}${a}`)}return r.entries}var Fa,kb,Pb,kp,wI,Op=v(()=>{"use strict";Fa=I(require("node:os"));F();dm();sn();kb=I(require("ajv"));ie();rl();W();Cb();Pb=1,kp="JSON file supplied to --mock-network-pattern",wI=P("prepare runner")});function Ub(s){return s.start&&gn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Fb(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=vo(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 Bb=v(()=>{"use strict";Cn();rs();Y()});var jb,xI,AI,Np,$b=v(()=>{"use strict";jb="TST_CREDS",xI=["username","password"],AI="$encrypted",Np={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of xI)t[r]={[AI]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(jb)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[jb]:this.proxyPlaceholder})}}});var jp={};H(jp,{doLogin:()=>Bp,getProjectId:()=>CI,getToken:()=>PI});async function CI(){return Gb("projectId")}async function PI(){return Gb("token")}function Vb(s,e){return Promise.race([s,ce(e).then(()=>{throw new oe("timeout")})])}async function kI(){let s=(await import("express")).default(),e=async function(){return Vb(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(),Re)),{editorUrl:n}=await r();uo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Bp({overwriteExisting:s=!0,projects:e=null}={}){let t=Mp.homedir(),r=Up.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Vb(kI(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,l.succeed(),await Wb(r,i);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=c.project.ci.token,i.projectId=c.project.id,await Wb(r,i);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Wb(s,e){await Fp.promises.writeFile(s,ja.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function Gb(s){let e=Mp.homedir(),t=Up.join(e,".testim"),r=await ye(t),n={};if(r)try{n=ja.parse((await Fp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Mp,Up,ja,Fp,$a=v(()=>{"use strict";Mp=I(require("os")),Up=I(require("path")),ja=I(require("yaml"));F();Fp=require("fs");Y();Ol()});var Qb={};H(Qb,{process:()=>FI});var Wp,Kb,Wa,Jb,Vt,De,Yb,OI,Le,Hp,_I,LI,qb,Xb,DI,Vp,Gp,qp,$p,Lt,NI,p,MI,UI,zb,FI,Zb=v(()=>{"use strict";Wp=I(require("ms")),Kb=I(require("chalk")),Wa=I(require("node:fs")),Jb=I(require("node:url")),Vt=I(require("lodash")),De=I(require("node:path"));F();Cn();Bb();Yt();Yb=require("commander");ie();Y();jr();F();ue();$b();Mo();OI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Le=(s,e)=>(e.push(s),e),Hp=new Yb.Command,_I=s=>s.split(","),LI=(s,e)=>!s||s.length===0?e:s,qb=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Xb=()=>{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 l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}Hp.help(g=>g.split(`
402
+ const downloadAndUploadFile = ${OE()};
403
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Sy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var pa,da,Ry=v(()=>{"use strict";pa=require("url");pe();da=class extends V{async updateBaseUrl(e){let t=new pa.URL(e),r=new pa.URL(this.context.recordedBaseUrl),n=new pa.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var ma,xy=v(()=>{"use strict";pe();F();ma=class extends V{async performAction(){await ce(this.step.durationMS||0)}}});var fa,Ay=v(()=>{"use strict";pe();fa=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Kn,Cy=v(()=>{"use strict";pe();Kn=class extends V{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 ga,Py=v(()=>{"use strict";pe();ga=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var ky,Fu,Bu,Oy=v(()=>{"use strict";ky=I(require("@applitools/spec-driver-webdriverio"));mi();we();Fu=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=dd["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:ky.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Z(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Bu=new Fu});var Ly,_y,Jn,Dy=v(()=>{"use strict";Ly=I(require("lodash"));pe();W();Oy();_y=P("pixel-validation-step-action"),Jn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Bu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Ly.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),_y.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){_y.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Bu.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ss,ju=v(()=>{"use strict";hs();Y();ta();Ss=class extends ir{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await gs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var or,Ny=v(()=>{"use strict";ju();or=class extends Ss{isFailedResult(e){return e===!1}}});var ha,My=v(()=>{"use strict";ju();ha=class extends Ss{isFailedResult(e){return!e}}});var ya,Uy=v(()=>{"use strict";hs();pe();Y();ya=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await fs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Lr,Fy=v(()=>{"use strict";pe();Lr=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,By=v(()=>{"use strict";pe();be=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ba,jy=v(()=>{"use strict";pe();ba=class extends V{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 Ta,$y=v(()=>{"use strict";pe();Ta=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function _E(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function wa(s,e){_E(LE,e),e.registerLocateStepActionUtils(Gn.getUtils(s))}var LE,$u=v(()=>{"use strict";Uh();jh();Jh();Yh();Qh();ty();ny();iy();oy();ay();uy();py();dy();gy();by();Iy();Ry();xy();Ay();Cy();Py();Dy();Ny();My();Uy();Fy();By();jy();$y();LE={locate:Gn,scroll:Yo,mouse:Xo,submit:ia,text:Zo,"special-key":ra,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":vs,"skip-code-step":vs,"element-code-step":vs,"evaluate-expression":Qo,"text-validation":qn,"wait-for-text-validation":qn,"select-option":na,"drop-file":ca,"input-file":ua,hover:oa,navigation:da,wheel:aa,sleep:ma,refresh:fa,"keyboard-shortcut-step":sa,"api-validation":Kn,"api-action":Kn,"api-code-step":Wt,"extract-text":ga,"simple-ui-verification":Jn,"wait-for-simple-ui-verification":Jn,"cli-validation-download-file":Lr,"cli-wait-for-download-file":Lr,"network-validation-step":Lr,"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":ha,"node-package":ya,"email-code-step":Wt,"cli-email-code-step":or,"sfdc-internal-test-step":Ta,"sfdc-recorded-step":ba,"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":Lr,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var Wy,DE,Es,Wu=v(()=>{"use strict";Wy=["simple-ui-verification","wait-for-simple-ui-verification"],DE=[...Wy,"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"],Es=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=DE.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 Wy.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 Gy={};H(Gy,{SeleniumTestPlayer:()=>Yn});var Vy,NE,Yn,Vu=v(()=>{"use strict";F();Vy=require("@applitools/eyes-sdk-core");Ln();Y();W();_u();_h();Mu();Ko();Nh();Uu();we();$u();Wu();NE=P("SeleniumTestPlayer"),Yn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(Jo());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Z();this.driver=n??new Ar;let d=new zo(this.driver);this.stepActionFactory=new c(d),wa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ho(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Dh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:qo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Vy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){NE.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Hu={};H(Hu,{WorkerSelenium:()=>Gu});function UE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var va,ME,Gu,qu=v(()=>{"use strict";F();je();Wn();W();Pt();Po();ie();ku();Y();Vu();we();at();va=P("worker-selenium"),ME=1e9,Gu=class extends Ot{initPlayer(t){return new Yn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){M("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ts(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,ME),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(va.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Ki(),initializedFromCache:Ji()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),UE(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await Mn(this.options))[this.testId]);let d=async()=>le(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof oe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(va.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=o.maxKeepAliveGap();f>=3e4&&(va.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw va.error("failed to run test once",{err:u}),u}}}});var Hy,qy,Ge,FE,BE,zu,vt,Sa=v(()=>{"use strict";Hy=I(require("ora")),qy=require("jimp");de();Ve();ge();W();ie();we();ue();Ge=P("mobile-grid-service"),FE="https://tdc.tricentis-cloud.com",BE="https://ui.headspin.io",zu=class{constructor(){this.gridsAppIdGetter={[L.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[L.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[L.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[L.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[L.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[L.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===L.TESTIM_HEADSPIN?`${r||oc}/${cc}/devices`:t===L.TESTIM_TDC?`${r||ac}/${cc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:i})}catch(o){throw Ge.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw Ge.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Gs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===L.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===L.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([L.BROWSERSTACK,L.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,l,c;if(t===L.TESTIM_HEADSPIN||t===L.TESTIM_TDC){let d=await Qn({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=Z();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Ir(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),Ge.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await qy.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/c.width,width:u,height:f}}catch(o){return Ge.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Us}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?BE:FE}/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:l}=t,c=await this.getTmaDeviceDetails(l,e);return await Ir(a,n,i,o,"RUNNING",{device:c}),Ge.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:c}),c}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(_.flags.allowFixingAppIdStructure.isEnabled()&&(Ge.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ju({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 Xn({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/(Ad*60))+1)*60*1e3,Math.max(xd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[L.BROWSERSTACK]:{name:"Browserstack"},[L.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[L.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Hy.default)(`uploading app to ${a} please wait..`).start();try{Ge.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Ku({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){Ge.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else Ge.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===L.BROWSERSTACK||f===L.TESTIM_TVC||f===L.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(Ge.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&Ge.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Us}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${lc}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?oc:ac}/${lc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Cd}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&Ge.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===L.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await Tc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},vt=new zu});function zy({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 $E({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==L.TESTIM_TDC&&e.type!==L.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function WE(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 VE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&_.flags.enableBatchHeadSpin.isEnabled(),d=o&&(_.flags.enableBatchTDC.isEnabled()||_.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=_.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,..._.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:WE(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Ea(s){return"id"in s?s.id:s.packageName}function GE(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function HE({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=GE(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":Ea(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":Ea(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Nr({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`]:Ea(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`]:Ea(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Ky({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let l=VE(o.type,i,n);return HE({projectType:s,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Ra({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function xa({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===L.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?uc:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":uc:".*")}function qE(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 zE(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ia(s,Is)}}function Jy(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 KE(s){return Jy(s,e=>e.startsWith("browserstack."),"browserstack.")}function JE(s){return Jy(s,e=>!e.startsWith("browserstack."))}function Yy(s){return!s||!Xy(s)?"2.0.0":s}function Xy(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Qy({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=Xy(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ia(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}async function YE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:l}){let{osVersion:c,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=qE(i,s),h=await Qn({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:S})=>{var E;return((E=m.staticAllocation)==null?void 0:E.deviceUdid)===S}),y=(g==null?void 0:g.osVersion)??Ra({osVersion:c,mobileConfig:m}),T=(g==null?void 0:g.name)??xa({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),w=qe(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,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:l})}function XE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=_.flags.enableAppium2pCloudy.isEnabled(),g=Ra({osVersion:l,mobileConfig:d}),y=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),w={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...w,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Pd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=zE(b)),t="",Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Is}})}function QE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Ra({osVersion:l,mobileConfig:d}),f=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Dr.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Qy({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:Yy(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ia(h,Is),"sauce:options":{...T,...w,...(0,Dr.omit)(g,"appiumVersion")}};return Nr({projectType:s,sessionCaps:b,appiumPrefix:Is,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 Nr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function ZE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Ra({osVersion:l,mobileConfig:d}),f=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=KE(n.browserstack),g=(0,Dr.omit)(JE(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:w}=n.browserstack||{},b=_.flags.enableAppium2BrowserStack.isEnabled();if(b||Qy({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":Yy(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},A={"appium:platformVersion":u,"appium:deviceName":f,...Ia(g,Is),"bstack:options":{...E,...(0,Dr.omit)(h,"appiumVersion")}};return Nr({projectType:s,sessionCaps:A,appiumPrefix:Is,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let S={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:w||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ia(h,"browserstack.")};return Nr({projectType:s,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}async function eI(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Ky(s);if(L.TESTIM_TVC===s.gridInfo.type)return await YE(s);if(L.P_CLOUDY===s.gridInfo.type)return XE(s);if(L.SAUCELABS===s.gridInfo.type)return QE(s);if(L.BROWSERSTACK===s.gridInfo.type)return ZE(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function tI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}async function Zy(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}`);zy({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=await eI(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=tI(r,i==null?void 0:i.mobile);if(!(0,Dr.isEmpty)(T)){let w=Object.entries(T).map(([b,S])=>S.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=w}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=_.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Yu.default)("2m"),f=(0,Yu.default)("12m"),h=mr(_.flags.appiumConnectionRetryCount.getValue(),m),g=mr(_.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function eb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;zy({nativeAppMetadata:r,appPath:i,gridInfo:t}),$E({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=Ky({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function tb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Nr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function rb(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 Yu,Dr,Is,jE,Xu=v(()=>{"use strict";Yu=I(require("ms"));ue();ie();Sa();Dr=require("lodash");F();de();ge();Is="appium:",jE=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var Aa,nb=v(()=>{"use strict";Aa=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Ca,ib=v(()=>{"use strict";F();Ca=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Xs;this.getLinksFromUnescapeHTML=Qs}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 Qu,Pa,ob=v(()=>{"use strict";W();Qu=P("mobile-frame-locator-mock"),Pa=class{foundFrameCallback(){return Qu.info("foundFrameCallback-mock invoked"),{}}locate(){return Qu.info("locate-mock invoked"),{}}async findFrame(){return Qu.info("findFrame-mock invoked"),{}}}});var rI,cb,ab,Rs,Zu=v(()=>{"use strict";rI=I(require("webdriverio")),cb=require("@applitools/eyes-sdk-core");nb();Mu();W();ib();Uu();we();$u();ob();Wu();ab=P("appium-test-player"),Rs=class{constructor(e,t,r,n=rI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Z(),m=new Ca(this.driver);this.stepActionFactory=new c(m),wa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(Jo()),this.sessionPlayer=new a(e,{tabService:new Aa,cookieUtils:void 0,FrameLocator:Pa,portSelector:qo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:cb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),ab.info("appium session deleted",{...i}))}catch(o){ab.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 sI(s){return await Te(`${s}/api/status`)}async function lb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function ub(s){if((await sI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var pb=v(()=>{"use strict";Ve()});var db={};H(db,{WorkerLocalTma:()=>sp});var Mr,ep,tp,rp,sp,mb=v(()=>{"use strict";Ve();Xu();Wn();F();W();Pt();Zu();we();pb();Sa();Mr=P("worker-appium"),ep=class extends Error{},tp=class extends Error{},rp=class extends Error{},sp=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Rs(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:l}=this.options;await ub(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:A}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:w,version:b},S]=await Promise.all([this.getAppStateFromDevice(o,a,T),lb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Mr.info("device status and app state",{deviceStatus:S,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),Mr.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=tb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),j={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:j,executionId:this.executionId,testResultId:this.testResultId});let R=await this.requestNewAppiumSessionFromTma(o,j,g);this.sessionData=R;let x=await m.attach({sessionId:R.sessionId,capabilities:D,options:{capabilities:D}});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:x.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:x.capabilities})}catch(A){throw Mr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new rp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await Te(o)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Mt(n);await Vs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new tp(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new ep(`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},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var gb={};H(gb,{WorkerAppium:()=>np});var fb,Ur,np,hb=v(()=>{"use strict";F();Xu();fb=require("linkedom");Wn();W();Pt();Zu();we();Sa();ie();os();Ur=P("worker-appium"),np=class extends Ot{initPlayer(t){return new Rs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==L.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:l}=n,c=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),d=o==="android"?t.androidActivityWait:null,m=t.nativeAppMetadata;if(!m)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:o,nativeAppMetadata:m,appPath:c,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(i,this.options.deviceUdid),h=await eb(f)):h=await Zy({...f,shouldRunInEnhancedMode:a}),Ur.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:rb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await l.remote(h),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Ur.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Ur.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){Ur.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"&&Mf(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){Ur.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:S}=await vt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${S}`}else d=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,fb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Ur.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(),c)}catch(y){throw Ur.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:runner-v4.147.0"}}});var ka,yb=v(()=>{"use strict";F();Ln();Y();ka=class{constructor(e){this.id=e;this.driver=new Ar}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var bb,Oa,Tb=v(()=>{"use strict";bb=I(require("ws"));F();Oa=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new bb.default(this._cdpUrl,{timeout:e}),r=Kt(i=>{t.once("open",i)}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var La,ip,_a,wb=v(()=>{"use strict";F();La=I(require("chrome-launcher"));eu();Tb();En();ip=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Oa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Ro({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...La.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await La.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 gr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),as(()=>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}},_a=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new ip(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var op={};H(op,{WorkerExtension:()=>Zn});function nI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function vb(s){return nI(s)?s:new Error(s)}var dt,Zn,Da=v(()=>{"use strict";je();Y();Wn();F();W();Pt();ie();yb();wb();at();dt=P("worker-ext"),Zn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new ka(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw dt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Ki(),initializedFromCache:Ji(),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;M("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(d.cdpTestRunner),m,Me.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))throw u;return dt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw dt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(M("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw dt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Me.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;dt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),dt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=qs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=le(e.onCompleted(),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG),w=await gc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(E){dt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(dt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(dt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw dt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),vb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw dt.warn("failed to start url",{err:h}),vb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await c()}catch(d){throw dt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var cp={};H(cp,{WorkerExtensionSingleBrowser:()=>ap});var iI,oI,ap,lp=v(()=>{"use strict";je();F();W();xu();Pt();Da();iI=P("base-worker"),oI=500,ap=class extends Zn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await jn(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,i){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(iI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let i=this.handleQuarantine(t);if(i)return i;M("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ce(oI)}}});var up,Na,Sb=v(()=>{"use strict";Ln();de();je();hl();at();au();Y();W();ie();gh();Mo();up=P("worker-manager"),Na=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(qu(),Hu))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(mb(),db))).WorkerLocalTma:(await Promise.resolve().then(()=>(hb(),gb))).WorkerAppium;default:return Dn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(lp(),cp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Da(),op))).WorkerExtension}else switch(r){case(Or.find(n=>n===r)&&Dn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(lp(),cp))).WorkerExtensionSingleBrowser;case Or.find(n=>n===r):return(await Promise.resolve().then(()=>(Da(),op))).WorkerExtension;case Bn.find(n=>n===r):return(await Promise.resolve().then(()=>(qu(),Hu))).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 M("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var fe,Ze,St,Br,k,N,$,K;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new No(r,n,e,i,o,t),this.combinedTestResults={};let T=((fe=i.company)==null?void 0:fe.ucid)||"",w=(Ze=i.company)==null?void 0:Ze.companyId,b=(St=i.company)==null?void 0:St.name,S=i.source||"cli",E=i.user,A=(Br=i.company)==null?void 0:Br.planType,D=(k=i.company)==null?void 0:k.isStartUp,j=(N=i.projectData)==null?void 0:N.name,R=($=i.projectData)==null?void 0:$.type,x=i.lightweightMode,O=(K=i.gridData)==null?void 0:K.type,B=(Pe,Et,ve,Qa,ni,Za)=>(d++,wf({executionId:r,projectId:g,testId:Et,resultId:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,isStartUp:D,projectType:R,appSource:Za,gridType:O}),t.testStartAndReport(Pe,r,ve,Qa,ni)),G=async(Pe,Et,ve,Qa,ni,Za)=>{var od,ad,cd;d--;let et={...(x==null?void 0:x.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||((od=i.gridData)==null?void 0:od.name),et.gridType=(ad=i.gridData)==null?void 0:ad.type,et.gridProvider=(cd=i.gridData)==null?void 0:cd.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(Pe,ve,r,Qa,ni,et).catch(BT=>up.error("testEndAndReport threw an error",{err:BT})),ni)return;this.combinedTestResults[ve.resultId]=ve,vf({executionId:r,projectId:g,testId:Et,resultId:ve.resultId,result:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,logger:up,isStartUp:D,projectType:R,appSource:Za}),l&&!ve.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},z=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},X=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...wr(),refreshToken:qi(),authData:wr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,B,G,X,z)});try{let u=await At(),f=await zi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw up.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var pp,ae,Eb=v(()=>{"use strict";pp=class{static colorString(e,t){return`${e}${t}${pp.Reset}`}},ae=pp;ae.Reset="\x1B[0m",ae.Bright="\x1B[1m",ae.Dim="\x1B[2m",ae.Underscore="\x1B[4m",ae.Blink="\x1B[5m",ae.Reverse="\x1B[7m",ae.Hidden="\x1B[8m",ae.FgBlack="\x1B[30m",ae.FgRed="\x1B[31m",ae.FgGreen="\x1B[32m",ae.FgYellow="\x1B[33m",ae.FgBlue="\x1B[34m",ae.FgMagenta="\x1B[35m",ae.FgCyan="\x1B[36m",ae.FgWhite="\x1B[37m",ae.FgGray="\x1B[90m",ae.BgBlack="\x1B[40m",ae.BgRed="\x1B[41m",ae.BgGreen="\x1B[42m",ae.BgYellow="\x1B[43m",ae.BgBlue="\x1B[44m",ae.BgMagenta="\x1B[45m",ae.BgCyan="\x1B[46m",ae.BgWhite="\x1B[47m",ae.BgGray="\x1B[100m"});var ei,Ib,Ma,dp,mp,Fr,fp=v(()=>{"use strict";ei=I(require("lodash"));F();W();de();ie();je();ts();gl();hl();ge();ue();Pt();ag();Y();Sb();Mo();Ib=require("uuid");Eb();({CLI_MODE:Ma}=Ut),dp=P("test-plan-runner"),mp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return mp._id}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Na(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,g,y);Object.assign(c,T)},u=async()=>{let g=hi||i.parallel,y=!1;M("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);M("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};Sf({executionId:o,projectId:i.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),c}catch(g){if(dp.error("error running test plan",{err:g}),g instanceof qt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Ma.SELENIUM){let[{getSessionPlayer:S},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(we(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=S();await A.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await bp(i.project),ei.default.isEmpty(g)||!o))return;let{runKey:S,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:S}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,S,E;let c=re(),d=n.project;$d(c),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new bo(m,n,o,a),f=ei.default.chain(m).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);M("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),M("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return M("before executionEnd"),await u.executionEnd(c),M("after executionEnd"),{results:w,executionId:c,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(ae.colorString(ae.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await gp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await hp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){dp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return ei.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};_.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async d=>{let m=await ti(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await se(e.testPlan,async d=>{let m=await ti(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await ti(o,e.testPlan,e.testPlanIds,t,e.intersections);let l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Ma.APPIUM&&await Iu(e,r(c)),await se(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await af(e,d);let f=u.overrideExecutionName||d.name;return await se(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Eu(n[m][E])})),w=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,A)=>Object.assign(E,A),{}),b=Eu(w);Object.assign(i,w);let S=b?T[0].executionId:T.find(E=>!E.status).executionId;return await yp(o,m,{success:b,executions:T,executionId:S}),y})})}async runAnonymousTestPlan(e,t){var l;dp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await yh(e,t);if(M("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.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;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Ma.APPIUM&&(a=await Xn({appId:e.appId,projectId:e.project})),await se(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Ma.APPIUM&&await Iu(e,c),M("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return M("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=fn(),r=[];await this.reportTestRunnerStarted(e.project,e),Ks(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ei.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Fr=mp;Fr._id=(0,Ib.v4)()});var Re={};H(Re,{addTestRetry:()=>Kl,clearTestResult:()=>vu,deleteCloudflareTunnel:()=>xp,fetchLambdatestConfig:()=>Yl,fixGridAppIDStructure:()=>Ju,forceUpdateCloudflareTunnelRoutes:()=>Rp,getAllGrids:()=>fl,getAppDetails:()=>Xn,getApplitoolsIntegrationData:()=>bp,getBrowserStackSessionMetaData:()=>hI,getCloudflareTunnel:()=>Ip,getEditorUrl:()=>mI,getGridSlot:()=>ml,getHybridGridProvider:()=>dl,getLabFeaturesByProjectId:()=>cu,getMobileDevicesFromGrid:()=>Qn,getRealData:()=>$l,getS3Artifact:()=>xn,getS3ArtifactText:()=>jl,getSuiteTestList:()=>Ru,getTestPlan:()=>dI,getTestPlanTestList:()=>ti,getTestResults:()=>kr,getUsageForCurrentBillingPeriod:()=>Sp,initializeUserWithAuth:()=>Ep,isTestResultCompleted:()=>wu,keepAliveCompanySlots:()=>Fl,keepAliveGrid:()=>ul,loadSfdcCredential:()=>vp,loadTest:()=>Un,releaseCompanySlot:()=>Ml,releaseGridSlot:()=>pl,reportExecutionFinished:()=>To,reportExecutionStarted:()=>zl,reportRunnerFinished:()=>hp,reportRunnerStarted:()=>gp,requestCompanySlot:()=>Nl,saveRemoteStep:()=>uu,saveTestPlanResult:()=>yp,updateCompanySlot:()=>Ul,updateExecutionTests:()=>ql,updateRemoteRunFailure:()=>Ap,updateTestDataArtifact:()=>wo,updateTestResult:()=>jo,updateTestStatus:()=>Ir,uploadAppToGrid:()=>Ku,uploadRunDataArtifact:()=>Su,validateUserAccessKey:()=>cl});async function xs(){let s=await At();if(!s)throw new Error("Failed to get token from server");return{[_c]:Fr.id,Authorization:`Bearer ${s}`}}async function Ee({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await xs(),o={...t,...i};return We({url:`${he}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function uI(s,e,t,r={},n=void 0){let i=await xs(),o={...r,...i};return await Vs(`${he}${s||""}`,e,t,o,n)}async function ri(s,e){let t=await xs();return await wc(`${he}${s||""}`,e,t)}async function xb(s,e){let t=await xs();return await Ws(`${he}${s||""}`,e,t)}async function pI(s,e){let t=await xs();return await Gs(`${he}${s||""}`,e||void 0,t)}async function Ae(s,e,t,r){let n=await xs();return await Te(`${he}${s||""}`,e||void 0,n,r,t)}function xn(s,e){return(0,ee.default)(()=>Ae(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function jl(s){return(0,ee.default)(()=>pI(`/storage${s}`))}async function gp(s,e){return await Ee({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function hp(s){return await xb("/test-runner",{projectId:s})}async function dI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>Ae("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function vp({branch:s,projectId:e}){let t=await(0,ee.default)(()=>Ae(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function Un({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>Ae(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function yp(s,e,t){return(0,ee.default)(()=>Ee({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Ir(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>ri("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:aI,...i}),{retries:o,factor:1})}function ql(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>ri("/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 zl({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Zi(),yf));return Ee({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function To(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>ri("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function ti(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Ru({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,ee.default)(()=>Ee({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:te,factor:1})}async function Xn({appId:s,projectId:e}){try{return await(0,ee.default)(()=>Ae(`/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 Sp(s){try{return await(0,ee.default)(()=>Ae(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){_t.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function wu(s,e,t){return(0,ee.default)(()=>Ae(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function kr(s,e,t,r){return(0,ee.default)(()=>Ae(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function ul(s,e){return Ee({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function pl(s,e,t,r,n){return Ee({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function dl(s){return Ee({url:"/grid/hybrid/provider",body:s})}function ml(s){return(0,ee.default)(()=>Ae("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Ep({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d}){var m,u;try{return await(0,ee.default)(()=>We({url:`${he}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d},timeout:6e4}),{retries:te,factor:1})}catch(f){if(_t.error("error initializing info from server",f),(m=f.message)!=null&&m.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(Tp.default[y](Tp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{_t.error("Error parsing error message from server",f)}throw f}}async function mI(){if(Ns)return{editorUrl:Ns};try{return await(0,ee.default)(()=>Ae("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return _t.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function fl(s){return(0,ee.default)(()=>Ae("/grid",{companyId:s}),{retries:te,factor:1})}function $l(s,e,t){return(0,ee.default)(()=>Ae(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function jo(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function vu(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function uu(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function fI(s){return s.startsWith("/")?s:`/${s}`}function gI(s,e,t){let r=fI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Ab(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,l=`${e}/${t}/${a}`,c=gI(l,lI,s),d=Buffer.from(Rb.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,ee.default)(()=>uI(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),c}function Kl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Ee({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 bp(s){try{return await Ae(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return _t.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Ip(s,e){try{return await ri("/tunnel",{companyId:s,routes:e})}catch(t){return _t.warn("could'nt get tunnel.",{err:t}),{}}}async function Rp(s,e){try{return await Ee({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}async function xp(s,e){try{return await xb(`/tunnel/${e}`,{companyId:s})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}function Ap(s){return We({url:`${he}/result/remoteRunFailure`,body:s})}async function Qn({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${cI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>Ae(i,{projectId:s}),{retries:te,factor:1})}catch(o){return _t.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function Ku({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Ee({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function Ju(s){return(0,ee.default)(()=>Ee({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Nl(s,e){return(0,ee.default)(()=>Ee({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Ml(s,e,t){return(0,ee.default)(()=>Ee({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Ul(s,e,t){return(0,ee.default)(()=>ri("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Fl(s,e,t){return Ee({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function hI(s,e){return await Te(`${Us}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function cl(s){try{return await Ae("/v2/project/validateUserAccessKey",s),!0}catch(e){return _t.error("error validating user access key",{error:e}),!1}}var Tp,ar,Rb,ee,wp,aI,_t,te,cI,lI,Yl,cu,Su,wo,ge=v(()=>{"use strict";Tp=I(require("chalk")),ar=I(require("lodash")),Rb=I(require("pako"));F();de();ie();Ve();at();ee=I(require("p-retry")),wp=I(require("object-hash"));Y();W();fp();aI=tt(),_t=P("testim service api"),te=3,cI="/grid",lI="test-result-artifacts";Yl=async()=>(0,ee.default)(()=>Ae("/grid/lt/config"),{retries:te,factor:1}),cu=async s=>(0,ee.default)(()=>Ae(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Su=ar.memoize(async(s,e,t,r)=>{if(!ar.isEmpty(r))return await Ab(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,wp.default)(r)}:${e}:${t}`),wo=ar.memoize(async(s,e,t,r,n)=>!r||ar.isEmpty(r)?void 0:await Ab(s,e,t,JSON.stringify((()=>{let o=ar.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(c=>{o[c]&&Object.assign(o,{[c]:Pc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,wp.default)(r)}:${e}:${t}`)});async function Cb(){let s=await Promise.any(yI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var yI,Pb=v(()=>{"use strict";Ve();yI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});function Ua(){return tt()}var Cp=v(()=>{"use strict";F()});function wI(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(we(),He(tr)).getSessionPlayer()}catch{}})}function vI(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(Pp.default[i](Pp.default[n](r.text)))})}async function si(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?TI:bI,f=Ua(),h=xc(),g=await Dm(),y=null;if(_.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Cb()}catch(b){kb.error("failed to get public ip",b)}let T=!0;M("before initializeUserWithAuth");let w=await Bt(async()=>(wI(a),T=!1,await Ep({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:y,gridId:l,grid:c,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:y})();return vI(w),s.publicIps=[w.clientPublicIp],M("after initializeUserWithAuth"),y&&w.clientPublicIp&&w.clientPublicIp!==y&&(kb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:w.clientPublicIp}),s.publicIps.push(y)),ef(w.authData,{projectId:e,token:t,userAccessKey:r,publicIp:w.clientPublicIp,initializedFromCache:T}),w}var Pp,kb,bI,TI,Ob=v(()=>{"use strict";Pp=I(require("chalk"));je();ge();Yt();at();Pb();ie();W();ue();Cp();F();Zr();kb=P("initializeUserWithAuth"),bI=1e3*60*5,TI=1e3*60*60*10});async function Db(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Hi():s.chromeBinaryLocation,e=tn({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!==q.EXTENSION&&await br(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await Qc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Xc(s.installCustomExtension,n)}return await e,t}async function Nb(s){var o;SI.info("prepare MockNetwork",{location:s});let e=await Ic(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>_b*1e6)throw new Error(`${kp} exceeded ${_b}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${kp} cannot be parsed.${Fa.EOL}${a}`)}let n=new Lb.default;if(!n.validate(Bc,r)){let a=(o=n.errors)==null?void 0:o.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Fa.EOL);throw new Error(`${kp} is malformed.${Fa.EOL}${a}`)}return r.entries}var Fa,Lb,_b,kp,SI,Op=v(()=>{"use strict";Fa=I(require("node:os"));F();mm();sn();Lb=I(require("ajv"));ie();rl();W();Ob();_b=1,kp="JSON file supplied to --mock-network-pattern",SI=P("prepare runner")});function jb(s){return s.start&&gn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function $b(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=vo(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 Wb=v(()=>{"use strict";Cn();rs();Y()});var Vb,CI,PI,Np,Gb=v(()=>{"use strict";Vb="TST_CREDS",CI=["username","password"],PI="$encrypted",Np={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of CI)t[r]={[PI]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(Vb)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[Vb]:this.proxyPlaceholder})}}});var jp={};H(jp,{doLogin:()=>Bp,getProjectId:()=>kI,getToken:()=>OI});async function kI(){return zb("projectId")}async function OI(){return zb("token")}function qb(s,e){return Promise.race([s,ce(e).then(()=>{throw new oe("timeout")})])}async function _I(){let s=(await import("express")).default(),e=async function(){return qb(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(),Re)),{editorUrl:n}=await r();uo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Bp({overwriteExisting:s=!0,projects:e=null}={}){let t=Mp.homedir(),r=Up.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await qb(_I(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,l.succeed(),await Hb(r,i);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=c.project.ci.token,i.projectId=c.project.id,await Hb(r,i);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Hb(s,e){await Fp.promises.writeFile(s,ja.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function zb(s){let e=Mp.homedir(),t=Up.join(e,".testim"),r=await ye(t),n={};if(r)try{n=ja.parse((await Fp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Mp,Up,ja,Fp,$a=v(()=>{"use strict";Mp=I(require("os")),Up=I(require("path")),ja=I(require("yaml"));F();Fp=require("fs");Y();Ol()});var tT={};H(tT,{process:()=>jI,program:()=>p});var Wp,Xb,Wa,Qb,Vt,De,Zb,LI,Le,Hp,DI,NI,Jb,eT,MI,Vp,Gp,qp,$p,Lt,UI,p,FI,BI,Yb,jI,zp=v(()=>{"use strict";Wp=I(require("ms")),Xb=I(require("chalk")),Wa=I(require("node:fs")),Qb=I(require("node:url")),Vt=I(require("lodash")),De=I(require("node:path"));F();Cn();Wb();Yt();Zb=require("commander");ie();Y();jr();F();ue();Gb();Mo();LI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Le=(s,e)=>(e.push(s),e),Hp=new Zb.Command,DI=s=>s.split(","),NI=(s,e)=>!s||s.length===0?e:s,Jb=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],eT=()=>{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 l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}Hp.help(g=>g.split(`
404
404
  `).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!o(T)&&!i(T)&&!l(T)&&!c(T)&&!d(T)&&!m(T)&&!u(T)&&!f(T)&&!h(T)).join(`
405
- `))},DI=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(Kb.default.yellow(`
405
+ `))},MI=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(Xb.default.yellow(`
406
406
  WARNING: ${s} is deprecated. ${t}
407
- `))},Vp=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Gp,argv:qp,exit:$p,cwd:Lt}=global.process,NI=new Set(["trace","debug","info","warn","error","silent"]);Lc(qp,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Hp.description("Testim.io CLI").option("-h --help","output usage information",Xb).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",Le,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Le,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Le,[]).option("--test-id [test-id]","test ID to run",Le,[]).option("-l, --label [label]","labels to search test by",Le,[]).option("-n, --name [test-name]","test name to run",Le,[]).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",Le,[]).option("--test-plan-id [test-plan-id]","test plan to run",Le,[]).option("--suite [suite-name]","suite to run",Le,[]).option("--suite-id [suite-id]","suite ID to run",Le,[]).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",Le,[]).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(Gp.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,Wp.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,Wp.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: ${Vp.join("/")}`,Le,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Le,[]).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("--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",Le,[]).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)",Le,[]).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)",Le,[]).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(qp);p=Hp.opts(),MI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},UI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},zb=s=>{var r;if(!_.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=Wa.readFileSync(s);(r=Np)!=null&&r.containsEncryptedCredentials(t.toString())&&Np.injectProxyCredentialsStoreToGlobal()},FI=async()=>{var T,w,b,S,E,A,D,j;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!qp.slice(2).length)throw Xb(),new $r;if(p.version){let R="Testim CLI Version: ";Gp.npm_package_version&&(console.log(R,Gp.npm_package_version),$p(0));let x=tt();x&&(console.log(R,x),$p(0)),console.log("Could not find version, please check the package.json manually"),$p(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Im(),p.clearFileCache&&Xr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=De.resolve(n);Sm(R)}if(p.usePrefechedData&&Rm(),p.playerRequirePath){let R=De.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let x=De.join(R,"tsconfig.node.json"),B=require("ts-node").register({project:x,ignore:[/node_modules/,new RegExp(`^${Vt.escapeRegExp(De.relative(Lt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:B.config.options.paths,baseUrl:B.config.options.baseUrl}),(we(),He(tr)).options.playerPath=R;let z=require("node:module"),X=z.prototype.require;z.prototype.require=function(Ze){return Ze==="rox-alias"?X.call(this,"rox-node"):Ze==="canvas"?{}:X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Wa.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(Ub(p))return Fb(p);try{let R={};p.configFile?(zb(p.configFile),R=require(De.join(Lt(),p.configFile)).config):p.optionsFile&&(R=require(De.join(Lt(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(x=>{let O=OI(x);p[O]=LI(p[O],R[x])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}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)||((S=p.testPlanId)==null?void 0:S.length),a=((E=p.suite)==null?void 0:E.length)||((A=p.suiteId)==null?void 0:A.length);if(p.seleniumCapsFile)try{r=require(De.join(Lt(),p.seleniumCapsFile))}catch(R){throw new C(`Failed to parse selenium caps file file error: ${R.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(De.join(Lt(),p.chromeExtraPrefs))}catch(R){throw new C(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let x of R){let[O]=x.split("=");qb.includes(O)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(x),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(qb)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&zb(p.paramsFile),s={...s,...require(De.join(Lt(),p.paramsFile))}}catch(R){throw new C(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new C(`Failed to parse params string error: ${R.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&&(MI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(De.join(Lt(),p.sauceOptions)),x=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let B=R.browserName.toLowerCase();switch(B){case"microsoftedge":p.browser="edge";break;default:p.browser=B}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let O=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!x&&p.browser==="chrome"&&O)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new C(`Failed to parse saucelabs options file error: ${R.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&&(UI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(De.join(Lt(),p.browserstackOptions)),x=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(p.browser=R.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(R.browser_version)>=79&&(p.browser="edge-chromium"),!x&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new C(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(De.join(Lt(),p.perfectoOptions)),x={location:"US East",securityToken:p.perfectoToken};p.perfecto={...x,...R}}catch(R){throw new C(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(De.join(Lt(),p.testobjectOptions)),x={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...x,...R}}catch(R){throw new C(`Failed to parse test object options file error: ${R.message}`)}let l={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId}};if(p.testOptimization=l,!p.project){let x=await(await Promise.resolve().then(()=>($a(),jp))).getProjectId();if(x)p.project=x;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}_.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 d=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 x=await(await Promise.resolve().then(()=>($a(),jp))).getToken();if(x)p.token=x;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 m=R=>R<=0||!Number.isInteger(R);if(m(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(m(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(m(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(m(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(m(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(m(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(m(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Or,...Bn].includes(p.browser))throw new C(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!NI.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((j=p.host)!=null&&j.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Jb.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(x=>x.trim()).filter(Boolean);let R=p.resultLabel.filter(x=>x.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&fr()&&p.resultLabel.unshift(fr()),R.length)throw new C("A result label cannot exceed 250 characters")}let f=vo(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&&!Vt.inRange(Vt.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&&Vt.difference(p.codeCoverageReporter,Vp).length){let R=Vt.difference(p.codeCoverageReporter,Vp);throw new C(`invalid --code-coverage-reporter parameters ${R.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(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&y.length){let R=y.length>1?"are":"is";throw new C(`${y.map(x=>g[x]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=Wa.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new C(`failed to parse field file error: ${R.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&&(DI("--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 R={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"},x=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...x}}catch(R){throw new C(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.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&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
408
- 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"?fr():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:d,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 zp,BI,As,eT,tT,Kp,rT,sT=v(()=>{"use strict";F();Y();W();In();zp=P("testimNgrok"),BI=".whitelisted-ngrok.testim.io",As="",tT=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}${BI}`);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 lt("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(zp.info("replace https to http"),As=i.replace("https://","http://")):As=i,s.tunnelDiagnostics&&Kp(),s.baseUrl=As},Kp=async(s=!0)=>{try{let t=(await lt("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===As);console.log("ngrok stats",n),zp.info("ngrok stats",{tunnel:n})}catch(e){zp.error("error collecting ngrok stats",{err:e})}s&&(eT=setTimeout(()=>Kp(),1e4))},rT=async s=>{if(!As)return;clearTimeout(eT),s.tunnelDiagnostics&&await Kp(!1),await(await lt("ngrok")).disconnect(As)}});var cr,Yp,nT,$I,WI,Jp,Va,Ha,Ga,VI,iT,oT,aT=v(()=>{"use strict";cr=I(require("os")),Yp=I(require("fs")),nT=I(require("child_process"));F();ge();$I="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",WI={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"}},Jp=cr.tmpdir(),Va=`${Jp}/cloudflared`,Ha=null,Ga=null,VI=async()=>{if(await ye(Va))return;let e=WI[cr.platform()+cr.arch()];if(!e)throw new Error(`tunnel on ${cr.platform()+cr.arch()} platform is not supported.`);let t=e.extract?Jp+e.path:Va;await Ke(`${$I}/${e.path}`,t),e.extract&&await it(t,Jp),await Yp.promises.chmod(Va,"755")},iT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Ip(s.company.companyId,t),VI()]);Ha=r._id,Ga=nT.spawn(Va,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Rp(s.company.companyId,Ha),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Yp.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},oT=async s=>{let e=[];return Ha&&e.push(xp(s.company.companyId,Ha)),Ga&&e.push(new Promise((t,r)=>{Ga.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Ga.kill()})),await Promise.all(e)}});var Xp={};H(Xp,{connect:()=>za,disconnect:()=>Ka,serveTunneling:()=>qI});var qa,cT,lT,HI,za,Ka,qI,Qp=v(()=>{"use strict";sT();En();aT();at();qa=I(require("ora"));W();ie();Eo();cT=P("tunnel"),lT=s=>{var e;return[L.TESTIM_LAMBDATEST,L.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},HI=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===L.HYBRID&&s.gridData.tunnel==="cloudflare"},za=async s=>{if(!s.tunnel)return;let e=wr(),t;try{lT(s)?(t=(0,qa.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):HI(s)?(t=(0,qa.default)("Starting testim cloudflare tunnel...").start(),await iT(s)):(t=(0,qa.default)("Starting testim ngrok tunnel...").start(),await tT(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."),cT.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
409
- ${r.stdoutResult}`:n)}},Ka=async s=>{if(s.tunnel)try{lT(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await oT(s):await rT(s)}catch(e){let t="catch error - failed to close tunnel";throw cT.error(t,{err:e}),new Error(t)}},qI=async(s,e=new Promise(()=>{}))=>(await za(s),as(()=>Ka(s)),await e)});var mT={};H(mT,{init:()=>fR,run:()=>uR});async function zI(s){let e=s.project,t=await Sp(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"),gn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Fs}function JI(s,e){var i,o,a,l,c,d,m,u,f,h,g,y,T;let t=ki(e.activePlan),r=s.parallel;if(t==="free"&&r>pT)throw new C(`The free plan allows only ${pT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let w=(i=s.projectData)!=null&&i.type?KI[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}).
407
+ `))},Vp=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Gp,argv:qp,exit:$p,cwd:Lt}=global.process,UI=new Set(["trace","debug","info","warn","error","silent"]);Lc(qp,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Hp.description("Testim.io CLI").option("-h --help","output usage information",eT).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",Le,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Le,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Le,[]).option("--test-id [test-id]","test ID to run",Le,[]).option("-l, --label [label]","labels to search test by",Le,[]).option("-n, --name [test-name]","test name to run",Le,[]).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",DI).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",Le,[]).option("--test-plan-id [test-plan-id]","test plan to run",Le,[]).option("--suite [suite-name]","suite to run",Le,[]).option("--suite-id [suite-id]","suite ID to run",Le,[]).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",Le,[]).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(Gp.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,Wp.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,Wp.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: ${Vp.join("/")}`,Le,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Le,[]).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("--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",Le,[]).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)",Le,[]).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)",Le,[]).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(qp);p=Hp.opts(),FI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},BI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Yb=s=>{var r;if(!_.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=Wa.readFileSync(s);(r=Np)!=null&&r.containsEncryptedCredentials(t.toString())&&Np.injectProxyCredentialsStoreToGlobal()},jI=async()=>{var T,w,b,S,E,A,D,j;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!qp.slice(2).length)throw eT(),new $r;if(p.version){let R="Testim CLI Version: ";Gp.npm_package_version&&(console.log(R,Gp.npm_package_version),$p(0));let x=tt();x&&(console.log(R,x),$p(0)),console.log("Could not find version, please check the package.json manually"),$p(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Rm(),p.clearFileCache&&Xr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=De.resolve(n);Em(R)}if(p.usePrefechedData&&xm(),p.playerRequirePath){let R=De.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let x=De.join(R,"tsconfig.node.json"),B=require("ts-node").register({project:x,ignore:[/node_modules/,new RegExp(`^${Vt.escapeRegExp(De.relative(Lt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:B.config.options.paths,baseUrl:B.config.options.baseUrl}),(we(),He(tr)).options.playerPath=R;let z=require("node:module"),X=z.prototype.require;z.prototype.require=function(Ze){return Ze==="rox-alias"?X.call(this,"rox-node"):Ze==="canvas"?{}:X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Wa.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(jb(p))return $b(p);try{let R={};p.configFile?(Yb(p.configFile),R=require(De.join(Lt(),p.configFile)).config):p.optionsFile&&(R=require(De.join(Lt(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(x=>{let O=LI(x);p[O]=NI(p[O],R[x])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}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)||((S=p.testPlanId)==null?void 0:S.length),a=((E=p.suite)==null?void 0:E.length)||((A=p.suiteId)==null?void 0:A.length);if(p.seleniumCapsFile)try{r=require(De.join(Lt(),p.seleniumCapsFile))}catch(R){throw new C(`Failed to parse selenium caps file file error: ${R.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(De.join(Lt(),p.chromeExtraPrefs))}catch(R){throw new C(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let x of R){let[O]=x.split("=");Jb.includes(O)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(x),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(Jb)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&Yb(p.paramsFile),s={...s,...require(De.join(Lt(),p.paramsFile))}}catch(R){throw new C(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new C(`Failed to parse params string error: ${R.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&&(FI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(De.join(Lt(),p.sauceOptions)),x=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let B=R.browserName.toLowerCase();switch(B){case"microsoftedge":p.browser="edge";break;default:p.browser=B}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let O=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!x&&p.browser==="chrome"&&O)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new C(`Failed to parse saucelabs options file error: ${R.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&&(BI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(De.join(Lt(),p.browserstackOptions)),x=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(p.browser=R.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(R.browser_version)>=79&&(p.browser="edge-chromium"),!x&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new C(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(De.join(Lt(),p.perfectoOptions)),x={location:"US East",securityToken:p.perfectoToken};p.perfecto={...x,...R}}catch(R){throw new C(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(De.join(Lt(),p.testobjectOptions)),x={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...x,...R}}catch(R){throw new C(`Failed to parse test object options file error: ${R.message}`)}let l={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId}};if(p.testOptimization=l,!p.project){let x=await(await Promise.resolve().then(()=>($a(),jp))).getProjectId();if(x)p.project=x;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}_.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 d=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 x=await(await Promise.resolve().then(()=>($a(),jp))).getToken();if(x)p.token=x;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 m=R=>R<=0||!Number.isInteger(R);if(m(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(m(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(m(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(m(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(m(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(m(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(m(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Or,...Bn].includes(p.browser))throw new C(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!UI.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((j=p.host)!=null&&j.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Qb.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(x=>x.trim()).filter(Boolean);let R=p.resultLabel.filter(x=>x.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&fr()&&p.resultLabel.unshift(fr()),R.length)throw new C("A result label cannot exceed 250 characters")}let f=vo(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&&!Vt.inRange(Vt.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&&Vt.difference(p.codeCoverageReporter,Vp).length){let R=Vt.difference(p.codeCoverageReporter,Vp);throw new C(`invalid --code-coverage-reporter parameters ${R.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(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&y.length){let R=y.length>1?"are":"is";throw new C(`${y.map(x=>g[x]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=Wa.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new C(`failed to parse field file error: ${R.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&&(MI("--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 R={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"},x=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...x}}catch(R){throw new C(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.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&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
408
+ 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"?fr():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:d,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 Kp,$I,As,rT,sT,Jp,nT,iT=v(()=>{"use strict";F();Y();W();In();Kp=P("testimNgrok"),$I=".whitelisted-ngrok.testim.io",As="",sT=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}${$I}`);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 lt("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(Kp.info("replace https to http"),As=i.replace("https://","http://")):As=i,s.tunnelDiagnostics&&Jp(),s.baseUrl=As},Jp=async(s=!0)=>{try{let t=(await lt("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===As);console.log("ngrok stats",n),Kp.info("ngrok stats",{tunnel:n})}catch(e){Kp.error("error collecting ngrok stats",{err:e})}s&&(rT=setTimeout(()=>Jp(),1e4))},nT=async s=>{if(!As)return;clearTimeout(rT),s.tunnelDiagnostics&&await Jp(!1),await(await lt("ngrok")).disconnect(As)}});var cr,Xp,oT,VI,GI,Yp,Va,Ha,Ga,HI,aT,cT,lT=v(()=>{"use strict";cr=I(require("os")),Xp=I(require("fs")),oT=I(require("child_process"));F();ge();VI="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",GI={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"}},Yp=cr.tmpdir(),Va=`${Yp}/cloudflared`,Ha=null,Ga=null,HI=async()=>{if(await ye(Va))return;let e=GI[cr.platform()+cr.arch()];if(!e)throw new Error(`tunnel on ${cr.platform()+cr.arch()} platform is not supported.`);let t=e.extract?Yp+e.path:Va;await Ke(`${VI}/${e.path}`,t),e.extract&&await it(t,Yp),await Xp.promises.chmod(Va,"755")},aT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Ip(s.company.companyId,t),HI()]);Ha=r._id,Ga=oT.spawn(Va,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Rp(s.company.companyId,Ha),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Xp.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},cT=async s=>{let e=[];return Ha&&e.push(xp(s.company.companyId,Ha)),Ga&&e.push(new Promise((t,r)=>{Ga.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Ga.kill()})),await Promise.all(e)}});var Qp={};H(Qp,{connect:()=>za,disconnect:()=>Ka,serveTunneling:()=>KI});var qa,uT,pT,zI,za,Ka,KI,Zp=v(()=>{"use strict";iT();En();lT();at();qa=I(require("ora"));W();ie();Eo();uT=P("tunnel"),pT=s=>{var e;return[L.TESTIM_LAMBDATEST,L.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},zI=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===L.HYBRID&&s.gridData.tunnel==="cloudflare"},za=async s=>{if(!s.tunnel)return;let e=wr(),t;try{pT(s)?(t=(0,qa.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):zI(s)?(t=(0,qa.default)("Starting testim cloudflare tunnel...").start(),await aT(s)):(t=(0,qa.default)("Starting testim ngrok tunnel...").start(),await sT(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."),uT.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
409
+ ${r.stdoutResult}`:n)}},Ka=async s=>{if(s.tunnel)try{pT(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await cT(s):await nT(s)}catch(e){let t="catch error - failed to close tunnel";throw uT.error(t,{err:e}),new Error(t)}},KI=async(s,e=new Promise(()=>{}))=>(await za(s),as(()=>Ka(s)),await e)});var gT={};H(gT,{init:()=>hR,run:()=>dR});async function JI(s){let e=s.project,t=await Sp(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"),gn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Fs}function XI(s,e){var i,o,a,l,c,d,m,u,f,h,g,y,T;let t=ki(e.activePlan),r=s.parallel;if(t==="free"&&r>mT)throw new C(`The free plan allows only ${mT} 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?YI[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&w?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[w]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
410
410
  We'll use the maximum of ${b} for now. To use more, you can adjust your command or upgrade your plan.`),s.parallel=b);let S=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.tunnel;if(s.tunnel&&!S)throw new 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=(m=(d=e.activePlan)==null?void 0:d.premiumFeatures)==null?void 0:m.runInTurboMode;s.lightweightMode&&!E&&(console.warn(`
411
- Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((u=s.gridData)==null?void 0:u.type)===L.TESTIM_TVC){let w=e.tvcLicense.expireAt||1;if(Date.now()>w&&!e.churnedByL2C)throw new 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)===L.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(Jt(s)){if(_.flags.removeMobileTrialRestrictions.isEnabled())return;let w=e.tvcLicense,b=e.tdcLicense;if(w!=null&&w.isPaid||b!=null&&b.isPaid)return;let S=e==null?void 0:e.createdAt;if(new Date(S)<new Date(_.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 YI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await zI(s)}catch(t){if([C,Fs].some(r=>t instanceof r))throw t;Zp.error("could not validate cli account",{err:t})}}function XI(s){let e=wr();return mf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function QI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(_.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Tt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(_o(),rh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Lo(),ih));r.init(s)}}function ZI(s,e){let{branch:t,autoDetect:r}=s;if(cf(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function eR(s,e){let{id:t,type:r}=e,i=dT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&_.flags.sfdcHybridCompany.isEnabled(),o=fn();i&&(s.sfdcCredential=await vp({projectId:t,branch:o}))}function tR(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=ki(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<uT?uT:s.newBrowserWaitTimeout),_.setCompanyId(t),_.setIsPOC(i),_.setIsStartUp(o),_.setPlanType(a),Ct.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function rR(s,e){s.editorUrl=Ns||e.editorUrl}function sR(s,e){s.allGrids=e}function nR(s,e){s.authData=e}function iR(s,e){let{id:t,name:r,type:n,defaults:i}=e;_.setProjectId(t),_.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function oR(s){var e;s.gridData=await nf(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function aR(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function cR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(yt("user-override-file",t),s.mockNetworkRules=await _b(s.overrideMappingFile))}async function lR(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await YI(s),M("in runRunner before tunnel.connect"),await za(s),M("in runRunner after tunnel.connect");let a=await new Fr(e).run(s);return M("before tunnel.disconnect"),await Ka(s),await mR(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function pR(s){var e;Ct.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
411
+ Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((u=s.gridData)==null?void 0:u.type)===L.TESTIM_TVC){let w=e.tvcLicense.expireAt||1;if(Date.now()>w&&!e.churnedByL2C)throw new 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)===L.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(Jt(s)){if(_.flags.removeMobileTrialRestrictions.isEnabled())return;let w=e.tvcLicense,b=e.tdcLicense;if(w!=null&&w.isPaid||b!=null&&b.isPaid)return;let S=e==null?void 0:e.createdAt;if(new Date(S)<new Date(_.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 QI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await JI(s)}catch(t){if([C,Fs].some(r=>t instanceof r))throw t;ed.error("could not validate cli account",{err:t})}}function ZI(s){let e=wr();return hf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function eR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(_.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Tt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(_o(),ih));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Lo(),ch));r.init(s)}}function tR(s,e){let{branch:t,autoDetect:r}=s;if(pf(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function rR(s,e){let{id:t,type:r}=e,i=fT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&_.flags.sfdcHybridCompany.isEnabled(),o=fn();i&&(s.sfdcCredential=await vp({projectId:t,branch:o}))}function sR(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=ki(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<dT?dT:s.newBrowserWaitTimeout),_.setCompanyId(t),_.setIsPOC(i),_.setIsStartUp(o),_.setPlanType(a),Ct.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function nR(s,e){s.editorUrl=Ns||e.editorUrl}function iR(s,e){s.allGrids=e}function oR(s,e){s.authData=e}function aR(s,e){let{id:t,name:r,type:n,defaults:i}=e;_.setProjectId(t),_.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function cR(s){var e;s.gridData=await cf(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function lR(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function uR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(yt("user-override-file",t),s.mockNetworkRules=await Nb(s.overrideMappingFile))}async function pR(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await QI(s),M("in runRunner before tunnel.connect"),await za(s),M("in runRunner after tunnel.connect");let a=await new Fr(e).run(s);return M("before tunnel.disconnect"),await Ka(s),await gR(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function mR(s){var e;Ct.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
412
412
  \x1B[4m\x1B[36mOur Free grid offers basic service performance.
413
413
  If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
414
- `)}function dR(s,e,t){s==="redis"&&wn.start(t,e),s==="mongo"&&dn.start(e)}async function mR(s,e,t){s==="redis"&&await wn.end(t,e),s==="mongo"&&await dn.end(e)}async function fR(s){var h,g,y,T;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=QI(e,{disableResults:i||Boolean((t==null?void 0:t.disableResults)&&(r||n===q.SELENIUM)),disableRemoteStep:i||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,editorConfig:l,companyByProjectId:c,projectById:d,branchName:m,allGrids:u}=await si(s);if(c.disabled)throw new C("The company is disabled.");if(d.disabled)throw new C("The project is disabled.");if(s.printGrids){let w=u.sort((b,S)=>b.type.localeCompare(S.type));console.table(w.reduce((b,S)=>{class E{constructor(j,R){this.Type=j,this.Browsers=R}}let A=Object.entries(S.browsers||{"N/A":""}).map(D=>D.join(":")).join(", ");return b[S.name]=new E(S.type,A),b},{})),process.exit(0)}if(await o,M("after featureFlagsReady and socketConnected"),rR(s,l),tR(s,c),iR(s,d),aR(s,d),ZI(s,m),sR(s,u),nR(s,a),await eR(s,d),await oR(s),JI(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[ig(s)]),_.flags.clearRunnerFileCache.isEnabled())try{await Xr(),Zp.info("runner file cache cleared")}catch(w){Zp.error("failed to clear runner file cache",{err:w})}(g=s.lightweightMode)!=null&&g.disableLabs||await Dn.loadLabFeatures(d.id,c.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(_.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((T=s.lightweightMode)==null?void 0:T.type)==="turboMode"&&console.log(`
415
- 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`),dR(s.slotService,e,c.id),XI(e),await cR(s),pR(s);let f=fn();await Q.setOptions(s,f)}var dT,uT,pT,Zp,KI,uR,fT=v(()=>{"use strict";dT=I(require("lodash"));F();Qp();je();ts();os();rs();gl();ge();at();Yt();W();Pt();de();ie();Y();fp();ko();au();ue();bn();Op();Cn();uT=30*60*1e3,pT=1,Zp=P("runner");KI={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};uR=lR});function gT(s){s.get("/",(e,t)=>{let r=ed();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Ua()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());Bp({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var hT=v(()=>{"use strict";$a();td();Cp()});var rd,yT,Cs,Ja,bT=v(()=>{"use strict";rd=I(require("chalk"));hs();yT=require("express");W();Y();Cs=P("cli-router"),Ja=(0,yT.Router)();Ja.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!l||typeof c!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d,nodePackageParams:n.nodePackageParams};try{let u=await gs(t,r,n,i,o,a,l,c,d);u.success||(console.log(rd.default.red(u.result.resultValue)),Cs.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){Cs.error("failed to run cli code",{err:u,...m}),console.log(rd.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});Ja.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 l={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let c=await fs(t,r,n,i,o,a);Cs.info("installed packages successfully",l),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof Rt){Cs.error("failed to install node packages",{err:c,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof oe){Cs.error("timeout installing node package",{err:c,...l}),e.status(200).json({success:!1,code:"timeout"});return}Cs.error("failed to install node packages",{err:c,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var TT=v(()=>{"use strict";bT()});var ET={};H(ET,{orchestrateRoutes:()=>gR});function gR(s){let e=(0,vT.default)();e.disable("x-powered-by"),s(e),e.use(sd.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,ST.default)()),e.use(sd.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:$e||fd?"*":["http://localhost:3000","https://app.testim.io","https://staging.testim.io","https://playground.testim.io","https://app.staging.testim.cc","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return e.use("*",(0,wT.default)(r)),gT(e),e.use("/cliJs",Ja),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var wT,vT,sd,ST,IT=v(()=>{"use strict";wT=I(require("cors")),vT=I(require("express")),sd=I(require("body-parser")),ST=I(require("compression"));hT();TT();de()});var xT={};H(xT,{init:()=>hR});async function hR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(IT(),ET));return new Promise((i,o)=>{let a=()=>{};t&&(Ym(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let l=n(a),c=RT.createServer(l);c.listen(s,e),c.on("error",d),c.on("listening",m);function d(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 m(){let{port:u}=c.address();console.log(`Running on port: ${u}`),yR()}})}async function yR(){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 RT,AT=v(()=>{"use strict";RT=I(require("http"));at();Y()});var DT={};H(DT,{getStartedWithStart:()=>ed,runAgentMode:()=>vR});async function vR(s){var r;let e;if(await br(s.playerLocation,s.canary),s.startTestimBrowser){await IR();try{e=await ER(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(()=>(AT(),xT));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(Vu(),He($y)))},6e3),t.init(s)}function ed(){return _T}function CT(s){try{return process.kill(s,0)}catch{return!1}}async function SR(s,e,t){let r=lr.join(Ft,`chrome-${on}-process`),n=3e3,i=()=>{Ce.rmSync(r,{recursive:!0}),console.log(`
414
+ `)}function fR(s,e,t){s==="redis"&&wn.start(t,e),s==="mongo"&&dn.start(e)}async function gR(s,e,t){s==="redis"&&await wn.end(t,e),s==="mongo"&&await dn.end(e)}async function hR(s){var h,g,y,T;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=eR(e,{disableResults:i||Boolean((t==null?void 0:t.disableResults)&&(r||n===q.SELENIUM)),disableRemoteStep:i||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,editorConfig:l,companyByProjectId:c,projectById:d,branchName:m,allGrids:u}=await si(s);if(c.disabled)throw new C("The company is disabled.");if(d.disabled)throw new C("The project is disabled.");if(s.printGrids){let w=u.sort((b,S)=>b.type.localeCompare(S.type));console.table(w.reduce((b,S)=>{class E{constructor(j,R){this.Type=j,this.Browsers=R}}let A=Object.entries(S.browsers||{"N/A":""}).map(D=>D.join(":")).join(", ");return b[S.name]=new E(S.type,A),b},{})),process.exit(0)}if(await o,M("after featureFlagsReady and socketConnected"),nR(s,l),sR(s,c),aR(s,d),lR(s,d),tR(s,m),iR(s,u),oR(s,a),await rR(s,d),await cR(s),XI(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[cg(s)]),_.flags.clearRunnerFileCache.isEnabled())try{await Xr(),ed.info("runner file cache cleared")}catch(w){ed.error("failed to clear runner file cache",{err:w})}(g=s.lightweightMode)!=null&&g.disableLabs||await Dn.loadLabFeatures(d.id,c.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(_.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((T=s.lightweightMode)==null?void 0:T.type)==="turboMode"&&console.log(`
415
+ 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`),fR(s.slotService,e,c.id),ZI(e),await uR(s),mR(s);let f=fn();await Q.setOptions(s,f)}var fT,dT,mT,ed,YI,dR,hT=v(()=>{"use strict";fT=I(require("lodash"));F();Zp();je();ts();os();rs();gl();ge();at();Yt();W();Pt();de();ie();Y();fp();ko();au();ue();bn();Op();Cn();dT=30*60*1e3,mT=1,ed=P("runner");YI={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};dR=pR});function yT(s){s.get("/",(e,t)=>{let r=td();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Ua()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());Bp({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var bT=v(()=>{"use strict";$a();rd();Cp()});var sd,TT,Cs,Ja,wT=v(()=>{"use strict";sd=I(require("chalk"));hs();TT=require("express");W();Y();Cs=P("cli-router"),Ja=(0,TT.Router)();Ja.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!l||typeof c!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d,nodePackageParams:n.nodePackageParams};try{let u=await gs(t,r,n,i,o,a,l,c,d);u.success||(console.log(sd.default.red(u.result.resultValue)),Cs.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){Cs.error("failed to run cli code",{err:u,...m}),console.log(sd.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});Ja.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 l={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let c=await fs(t,r,n,i,o,a);Cs.info("installed packages successfully",l),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof Rt){Cs.error("failed to install node packages",{err:c,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof oe){Cs.error("timeout installing node package",{err:c,...l}),e.status(200).json({success:!1,code:"timeout"});return}Cs.error("failed to install node packages",{err:c,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var vT=v(()=>{"use strict";wT()});var RT={};H(RT,{orchestrateRoutes:()=>yR});function yR(s){let e=(0,ET.default)();e.disable("x-powered-by"),s(e),e.use(nd.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,IT.default)()),e.use(nd.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:$e||gd?"*":["http://localhost:3000","https://app.testim.io","https://staging.testim.io","https://playground.testim.io","https://app.staging.testim.cc","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return e.use("*",(0,ST.default)(r)),yT(e),e.use("/cliJs",Ja),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var ST,ET,nd,IT,xT=v(()=>{"use strict";ST=I(require("cors")),ET=I(require("express")),nd=I(require("body-parser")),IT=I(require("compression"));bT();vT();de()});var CT={};H(CT,{init:()=>bR});async function bR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(xT(),RT));return new Promise((i,o)=>{let a=()=>{};t&&(Zm(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let l=n(a),c=AT.createServer(l);c.listen(s,e),c.on("error",d),c.on("listening",m);function d(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 m(){let{port:u}=c.address();console.log(`Running on port: ${u}`),TR()}})}async function TR(){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 AT,PT=v(()=>{"use strict";AT=I(require("http"));at();Y()});var MT={};H(MT,{getStartedWithStart:()=>td,runAgentMode:()=>ER});async function ER(s){var r;let e;if(await br(s.playerLocation,s.canary),s.startTestimBrowser){await xR();try{e=await RR(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(()=>(PT(),CT));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(Vu(),He(Gy)))},6e3),t.init(s)}function td(){return DT}function kT(s){try{return process.kill(s,0)}catch{return!1}}async function IR(s,e,t){let r=lr.join(Ft,`chrome-${on}-process`),n=3e3,i=()=>{Ce.rmSync(r,{recursive:!0}),console.log(`
416
416
 
417
- Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(Ce.readFileSync(r));if(CT(f.pid)){let h=()=>CT(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await Hi();await ye(Ps)||await Ce.promises.mkdir(Ps,{recursive:!0});let l=[...LT(Ps,e,t,o).desiredCapabilities.chromeOptions.args,...Xa.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],c={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await Xa.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Ps,chromePath:o,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await gr(`localhost:${m.port}`)};return Ce.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",i),m.process.once("close",i),{webdriverApi:u}}async function ER(s){let e=`${Ed}/extension/testim-full-master.zip`,t=lr.basename(e),r=lr.join(Ft,t),n=lr.join(Ft,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await ye(r)){let f=await Ce.promises.stat(r);i=Date.now()-TR>f.mtimeMs}if(await Ce.promises.mkdir(Ft,{recursive:!0}),i){let f=(0,kT.default)("Downloading Testim Editor").start();await Ke(e,r);try{await it(r,n)}catch{await Ce.promises.rm(r,{recursive:!0,force:!0}),await Ke(e,r);try{await it(r,n)}catch{throw await Ce.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 Ce.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Ce.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await SR(s,o,n);await tn({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=LT(Ps,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:l}=(Ln(),He(Mg)),{SeleniumPerfStats:c}=(ls(),He(Qf)),d=new l;d.seleniumPerfStats=new c;let m=await d.initClient(a);_T=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await gr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function LT(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&i.push(`--load-extension=${t}`),{logLevel:bR,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function IR(){if(await ye(Ya))try{let{webSocketDebuggerUrl:s}=await RR();await xR(s),await Ce.promises.unlink(Ya)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Ce.promises.unlink(Ya)}}async function RR(){let s=await Ce.promises.readFile(Ya,{encoding:"utf8"}),[e,t]=s.split(`
418
- `).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 gr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function xR(s,e=100){let t=await AR(s,e);return Kt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function AR(s,e=100){let t=new OT.default(s,{timeout:e}),r=Kt(i=>{t.once("open",i)}).then(()=>{t.removeAllListeners()}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}var PT,kT,OT,Ce,lr,Xa,bR,TR,Ps,wR,Ya,_T,td=v(()=>{"use strict";PT=I(require("ms")),kT=I(require("ora")),OT=I(require("ws")),Ce=I(require("fs")),lr=I(require("path")),Xa=I(require("chrome-launcher"));de();sn();Y();rl();F();bR=gi?"verbose":"silent",TR=(0,PT.default)("1h"),Ps=lr.join(Ft,"profile"),wR="DevToolsActivePort",Ya=lr.join(Ps,wR);_T=!1});var TN=require("source-map-support/register");var di=I(require("os")),Os=I(require("url")),_s=I(require("http")),ec=I(require("https")),oi=I(require("form-data")),ai=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)}},ci=class extends ai{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 oi.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()}},ks=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}},li=class extends Error{},ui=class extends Error{},pi=class extends Error{},ur=class extends Error{},Ie=class extends ai{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=_s.globalAgent;this.nodejsHttpsAgent=ec.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 (${di.type()} ${di.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Ie.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new ci(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){Ie.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&&!Os.parse(r,!1,!0).protocol)throw new li("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new pi(`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(Ie.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!==Ie.OPENED)throw new ur("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!==Ie.OPENED)throw new ur("XHR readyState must be OPENED");if(this._request)throw new ur("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new ui(`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
419
- `):""}overrideMimeType(t){if([Ie.LOADING,Ie.DONE].includes(this.readyState))throw new ur("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new ks("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new ui("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:"?_s:ec).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 oi.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 oi.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=_s.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(Ie.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ie.LOADING&&this._setReadyState(Ie.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ie.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(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new ks(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:Os.resolve(this.nodejsBaseUrl,t),a=Os.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"}},ke=Ie;ke.SyntaxError=li,ke.ProgressEvent=ks,ke.SecurityError=pi,ke.XMLHttpRequest=Ie,ke.InvalidStateError=ur,ke.XMLHttpRequestUpload=ci,ke.UNSENT=0,ke.OPENED=1,ke.HEADERS_RECEIVED=2,ke.LOADING=3,ke.DONE=4;Object.assign(global,{xhr2:ke,XMLHttpRequest:ke});var NT=I(require("semver"));je();Op();Yt();sn();var nd=I(require("chalk")),MT=require("events");ie();En();Y();ie();Zi();W();var Lb=I(require("os")),_p=I(require("path")),Lp=I(require("chalk")),Ba=require("fs");de();function Db(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=Lb.homedir();(0,Ba.mkdirSync)(_p.resolve(n,".testim_logs"),{recursive:!0});let i=_p.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}`),Td&&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(Lp.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(Lp.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Ba.writeFileSync)(i,`${s}
417
+ Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(Ce.readFileSync(r));if(kT(f.pid)){let h=()=>kT(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await Hi();await ye(Ps)||await Ce.promises.mkdir(Ps,{recursive:!0});let l=[...NT(Ps,e,t,o).desiredCapabilities.chromeOptions.args,...Xa.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],c={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await Xa.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Ps,chromePath:o,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await gr(`localhost:${m.port}`)};return Ce.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",i),m.process.once("close",i),{webdriverApi:u}}async function RR(s){let e=`${Id}/extension/testim-full-master.zip`,t=lr.basename(e),r=lr.join(Ft,t),n=lr.join(Ft,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await ye(r)){let f=await Ce.promises.stat(r);i=Date.now()-vR>f.mtimeMs}if(await Ce.promises.mkdir(Ft,{recursive:!0}),i){let f=(0,_T.default)("Downloading Testim Editor").start();await Ke(e,r);try{await it(r,n)}catch{await Ce.promises.rm(r,{recursive:!0,force:!0}),await Ke(e,r);try{await it(r,n)}catch{throw await Ce.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 Ce.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Ce.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await IR(s,o,n);await tn({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=NT(Ps,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:l}=(Ln(),He(Bg)),{SeleniumPerfStats:c}=(ls(),He(tg)),d=new l;d.seleniumPerfStats=new c;let m=await d.initClient(a);DT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await gr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function NT(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&i.push(`--load-extension=${t}`),{logLevel:wR,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function xR(){if(await ye(Ya))try{let{webSocketDebuggerUrl:s}=await AR();await CR(s),await Ce.promises.unlink(Ya)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Ce.promises.unlink(Ya)}}async function AR(){let s=await Ce.promises.readFile(Ya,{encoding:"utf8"}),[e,t]=s.split(`
418
+ `).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 gr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function CR(s,e=100){let t=await PR(s,e);return Kt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function PR(s,e=100){let t=new LT.default(s,{timeout:e}),r=Kt(i=>{t.once("open",i)}).then(()=>{t.removeAllListeners()}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}var OT,_T,LT,Ce,lr,Xa,wR,vR,Ps,SR,Ya,DT,rd=v(()=>{"use strict";OT=I(require("ms")),_T=I(require("ora")),LT=I(require("ws")),Ce=I(require("fs")),lr=I(require("path")),Xa=I(require("chrome-launcher"));de();sn();Y();rl();F();wR=gi?"verbose":"silent",vR=(0,OT.default)("1h"),Ps=lr.join(Ft,"profile"),SR="DevToolsActivePort",Ya=lr.join(Ps,SR);DT=!1});var vN=require("source-map-support/register");var di=I(require("os")),Os=I(require("url")),_s=I(require("http")),ec=I(require("https")),oi=I(require("form-data")),ai=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)}},ci=class extends ai{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 oi.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()}},ks=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}},li=class extends Error{},ui=class extends Error{},pi=class extends Error{},ur=class extends Error{},Ie=class extends ai{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=_s.globalAgent;this.nodejsHttpsAgent=ec.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 (${di.type()} ${di.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Ie.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new ci(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){Ie.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&&!Os.parse(r,!1,!0).protocol)throw new li("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new pi(`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(Ie.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!==Ie.OPENED)throw new ur("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!==Ie.OPENED)throw new ur("XHR readyState must be OPENED");if(this._request)throw new ur("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new ui(`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
419
+ `):""}overrideMimeType(t){if([Ie.LOADING,Ie.DONE].includes(this.readyState))throw new ur("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new ks("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new ui("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:"?_s:ec).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 oi.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 oi.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=_s.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(Ie.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ie.LOADING&&this._setReadyState(Ie.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ie.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(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new ks(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:Os.resolve(this.nodejsBaseUrl,t),a=Os.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"}},ke=Ie;ke.SyntaxError=li,ke.ProgressEvent=ks,ke.SecurityError=pi,ke.XMLHttpRequest=Ie,ke.InvalidStateError=ur,ke.XMLHttpRequestUpload=ci,ke.UNSENT=0,ke.OPENED=1,ke.HEADERS_RECEIVED=2,ke.LOADING=3,ke.DONE=4;Object.assign(global,{xhr2:ke,XMLHttpRequest:ke});var UT=I(require("semver"));je();Op();Yt();sn();var id=I(require("chalk")),FT=require("node:events");ie();En();Y();ie();Zi();W();var Mb=I(require("os")),_p=I(require("path")),Lp=I(require("chalk")),Ba=require("fs");de();function Ub(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=Mb.homedir();(0,Ba.mkdirSync)(_p.resolve(n,".testim_logs"),{recursive:!0});let i=_p.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}`),wd&&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(Lp.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(Lp.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Ba.writeFileSync)(i,`${s}
420
420
  ${s==null?void 0:s.stack}
421
421
 
422
- ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}en();var SI=P("process-handler"),Nb=!1;function EI(s){return s instanceof Error?1:Nb?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(me.SKIPPED)||[t,i].includes(me.FAILED)&&n===Je.EVALUATING?!1:r!==!0)?1:0)}function II(){try{Xt("chromedriver").stop()}catch{}}function Mb(){Nb=!0}async function Dp(s){s!=null&&s.stack&&(ss?console.error(s,s.stack):Db(s)),II(),await SI.waitForFlush(),process.exit(EI(s))}ge();W();ue();var CR=P("cli-entry");function PR(s){if(!NT.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=18,t=20,r=Number(process.versions.node.split(".")[0]),n=new Date("2025-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(nd.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function kR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(F(),J)),Promise.resolve().then(()=>(Zb(),Qb))]);M("Starting Testim.io CLI"),Nf(Dp);try{PR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await _.fetch();let t=await e.process();if(M("in main, after options.process"),Wd(global.proxyUri),MT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,$d(t.project),Em("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(()=>(In(),Bf));return await i()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Xr(),await si(t);let{preloadTests:i}=await Promise.resolve().then(()=>(Po(),Yg));await i(t),!t.playerRequirePath&&t.mode!==q.EXTENSION&&await br(t.playerLocation,t.canary);let o=await vm();o.success?console.log(`created prefetched data at ${Mi()}`):console.error("failed to create prefetch data",o.error);return}let r=await Promise.resolve().then(()=>(fT(),mT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:i}=await Promise.resolve().then(()=>(Qp(),Xp));await i(t);return}if(s.isAgentMode(t)){let{runAgentMode:i}=await Promise.resolve().then(()=>(td(),DT));return i(t)}if(t.saveRCALocally){let{initServer:i}=await Promise.resolve().then(()=>(Gl(),rg)),{port:o}=await i(t);t.localRCASaver=`http://localhost:${o}`}t.exitCodeIgnoreFailingTests&&Mb(),M("right before testRunner.init/prepareRunner.prepare"),await r.init(t);let n=await Ob(t);return M("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof $r)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Ap({...r,error:t.message}).catch(()=>{}),t instanceof C?(console.log(nd.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),CR.error("runner ended with unexpected error",{err:t}),t)}}kR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),Dp(s)});
422
+ ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}en();var II=P("process-handler"),Fb=!1;function RI(s){return s instanceof Error?1:Fb?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(me.SKIPPED)||[t,i].includes(me.FAILED)&&n===Je.EVALUATING?!1:r!==!0)?1:0)}function xI(){try{Xt("chromedriver").stop()}catch{}}function Bb(){Fb=!0}async function Dp(s){s!=null&&s.stack&&(ss?console.error(s,s.stack):Ub(s)),xI(),await II.waitForFlush(),process.exit(RI(s))}ge();W();ue();zp();var kR=P("cli-entry");function OR(s){if(!UT.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=18,t=20,r=Number(process.versions.node.split(".")[0]),n=new Date("2025-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(id.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(()=>(F(),J)),Promise.resolve().then(()=>(zp(),tT))]);M("Starting Testim.io CLI"),Ff(Dp);try{OR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await _.fetch({proxy:p.proxy});let t=await e.process();if(M("in main, after options.process"),Vd(global.proxyUri),FT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,Wd(t.project),Im("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(()=>(In(),Wf));return await i()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Xr(),await si(t);let{preloadTests:i}=await Promise.resolve().then(()=>(Po(),Zg));await i(t),!t.playerRequirePath&&t.mode!==q.EXTENSION&&await br(t.playerLocation,t.canary);let o=await Sm();o.success?console.log(`created prefetched data at ${Mi()}`):console.error("failed to create prefetch data",o.error);return}let r=await Promise.resolve().then(()=>(hT(),gT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:i}=await Promise.resolve().then(()=>(Zp(),Qp));await i(t);return}if(s.isAgentMode(t)){let{runAgentMode:i}=await Promise.resolve().then(()=>(rd(),MT));return i(t)}if(t.saveRCALocally){let{initServer:i}=await Promise.resolve().then(()=>(Gl(),ig)),{port:o}=await i(t);t.localRCASaver=`http://localhost:${o}`}t.exitCodeIgnoreFailingTests&&Bb(),M("right before testRunner.init/prepareRunner.prepare"),await r.init(t);let n=await Db(t);return M("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof $r)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Ap({...r,error:t.message}).catch(()=>{}),t instanceof C?(console.log(id.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),kR.error("runner ended with unexpected error",{err:t}),t)}}_R().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),Dp(s)});
423
423
  //# sourceMappingURL=cli.js.map