@testim/testim-cli 4.189.4 → 4.189.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.js +1 -1
- package/cli.js.map +3 -3
- package/npm-shrinkwrap.json +17 -16
- package/package.json +1 -1
package/cli.js
CHANGED
|
@@ -15,7 +15,7 @@ Testim had missing write access to ${s||e}
|
|
|
15
15
|
- exists in your PATH environment variables.
|
|
16
16
|
3. Try adding --chrome-binary-location flag to Testim CLI specifying the exact location of chrome binary in your computer (e.g on Windows "C:/Program Files/Google/Chrome/Application/chrome.exe").
|
|
17
17
|
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),i.fail(a),o}}async function sS(){let r=`${Zt}/sessionPlayer_LATEST_RELEASE`;return(await Gt(r)).body.toString("utf8")}async function iS(r,e){if(!De(r)||De(r)&&e||Me)return r;let t=await sS();return`${r}-${t}`}function Nl(){let r=yt();return us.resolve(r,"testim-bin")}function nS(){let r=Nl();return us.resolve(r,"sessionPlayer.zip")}async function qf(r,e,t=!1){try{return await Wn(r,e),await Ye(e,Nl())}catch(s){if(t)throw s;return await qf(r,e,!0)}}async function Rr(r,e){oo.info("prepare player",{location:r,canary:e});let t=nS();return ct(async()=>{let s=await iS(r,e);return await qf(s,t),{}},"preparePlayer",zf,[r,e,t])()}var Vf,Gf,us,Hf,oo,zf,_l,Wf,gi=E(()=>{"use strict";Vf=R(require("ms")),Gf=R(require("node:fs")),us=R(require("node:path"));ue();zt();Hf=require("serialize-error");W();xl();Q();U();oo=A("prepare runner and testim start"),zf=(0,Vf.default)("0.5 day"),_l=16,Wf=`The size of the custom extension is more than ${_l}MB`});function oS(){let r=hi.type().toLowerCase();return r==="darwin"?hi.arch()==="arm"?"mac_arm":"mac":r==="windows_nt"?hi.arch()==="x64"?"win64":"win32":"linux"}async function co(){let r=oS(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(r in t))throw new x(`Unsupported platform: ${r}`);let s=parseInt(yi,10)>591479?"chrome-win":"chrome-win32",i={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:s,win64:s},n={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},o=`${e}/${t[r]}/${yi}/${i[r]}.zip`,a=ao.join(Ml,i[r]),c=`${a}.zip`,l=ao.join(a,n[r]);if(await Te(l))return l;if(!await Te(c)){let m=(0,Fl.default)("Downloading Chromium").start();try{await Kf.promises.mkdir(Ml),await Xe(o,c)}catch(p){let f=`Failed to download Chromium: ${p.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,Fl.default)("Extracting Chromium").start();try{await Ye(c,Ml)}catch(m){let p=`Failed to extract Chromium: ${m.message}`;throw d.fail(p),new Error(p)}return d.succeed(),l}var Kf,hi,ao,Fl,yi,Ml,Ul=E(()=>{"use strict";Kf=R(require("fs")),hi=R(require("os")),ao=R(require("path")),Fl=R(require("ora"));Q();U();yi="1000968",Ml=ao.join(Tt,`chrome-${yi}`)});async function Yf(r,e){return xr=r,jl=e,await Bl()}function Qf(r,e){xr=e.projectId,jl=e.token,bi=e.userAccessKey,lt=r.token,wi=$l(lt),vi=r.refreshToken,Jf=e.publicIp,Xf=e.initializedFromCache}function cS(r=xr,e=jl){return ct(()=>(Ti.info("request to get cli token from server"),$e({url:`${be()}/auth/token`,body:{projectId:r,token:e}})),"getTokenV3",aS*10,{projectId:r,token:e})()}async function lS(){Ti.info("request to refresh JWT cli token from server");let r=await $e({url:`${be()}/auth/refreshToken`,body:{token:lt,refreshToken:vi}});return lt=r.token,wi=$l(lt),r.refreshToken&&(vi=r.refreshToken),lt}async function Bl(){try{let r=await cS();return Ti.info("successfully get cli token from server"),lt=r.token,wi=$l(lt),vi=r.refreshToken,lt}catch(r){throw r.message.includes("Unauthorized")?new x("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(Ti.error(`While trying to retrieve CLI token. caught error: ${r}`,{projectId:xr}),new x(`While trying to retrieve CLI token, caught error: ${r}`))}}function $l(r){return require("jsonwebtoken").decode(r).exp*1e3}async function Dt(){if(!wi)return Bl();let r=O.flags.accessTokenExpiryMargin.getValue();if(wi<Date.now()+4*r)try{return await lS()}catch(e){return Ti.error("failed to refresh token, executing fallback",e),Bl()}return lt}function lo(){return vi}function Si(){return lt?{uid:require("jsonwebtoken").decode(lt).id}:{}}async function uo(){if(!bi||!xr)return;if(await Wl({userAccessKey:bi,projectId:xr}))return bi;let e=`user access key "${bi}" is invalid for project "${xr}"`;throw new x(e)}function po(){return Jf}function mo(){return Xf}var Ti,lt,wi,vi,xr,jl,bi,Jf,Xf,aS,wt=E(()=>{"use strict";ue();We();zt();Q();W();fe();pe();Ti=A("testim-custom-token"),xr=null,jl=null,aS=300*1e3});var uS,Zf,eg,fo,go=E(()=>{"use strict";uS={testResultArtifacts:"test-result-artifacts",projectArtifacts:"test-projects-artifacts",runResultArtifacts:"run-result-artifacts"},eg=r=>{Zf=r},fo=()=>Zf??uS});function pS(r){if(r.protocol)return r.protocol;if([N.TESTIM_PRIVATE,N.TESTIM,N.BROWSERSTACK,N.SAUCELABS].includes(r.type)&&r.port===443)return"https";if([N.TESTIM_ENTERPRISE,N.TESTIM_LAMBDATEST,N.DEVICE_FARM].includes(r.type)){let e=tg.exec(r.host);return(e==null?void 0:e[2])||"https"}return""}function dS(r){let e=tg.exec(r);return e==null?void 0:e[3]}function yo(r){var w,S,C,_,B,V,I,k,L,j,G;let e=r&&dS(r.host),t=r.port,s=r.path,i=r&&pS(r),n=r.token,o=r.slotId,a=(w=r.hybrid)==null?void 0:w.tunnel,c=(S=r.external)==null?void 0:S.user,l=(C=r.external)==null?void 0:C.key,d=r.type,m=d===N.HYBRID?a&&((V=(B=(_=r.hybrid)==null?void 0:_.external)==null?void 0:B[r.hybrid.tunnel])==null?void 0:V.user):c,p=d===N.HYBRID?a&&((L=(k=(I=r.hybrid)==null?void 0:I.external)==null?void 0:k[r.hybrid.tunnel])==null?void 0:L.key):l,f=r.name,h=r&&(r._id||r.gridId),g=r.provider,b=(j=r.mobileTokens)==null?void 0:j.androidToken,T=(G=r.mobileTokens)==null?void 0:G.iosToken,v=r.apiUrl,y=r.isSupportGrid;return{host:e,port:t,path:s,protocol:i,accessToken:n,slotId:o,gridId:h,tunnel:a,user:c,key:l,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:p,androidToken:b,iosToken:T,apiUrl:v,isSupportGrid:y}}async function fS(r,e,t,s,i,n){var a;let o;try{o=await n()}catch(c){throw ut.error("failed to get grid",{projectId:r,companyId:e,err:c}),new Error(bt.UNKNOWN)}if(ut.info("get grid info",{...o,projectId:r,companyId:e}),!o||!["success","error"].includes(o.status))throw ut.error("invalid response - get grid",{res:o}),new Error(bt.UNKNOWN);if(o.status==="success"){if(o.grid.mode==="local")return{mode:"local"};((a=o.grid)==null?void 0:a.mode)==="custom"&&Object.assign(o.grid,ng(i));let c=yo(o.grid);return mS(t,e,c.gridId,c.slotId,s,c.isSupportGrid),c}throw o.code==="not-found"?new nt(bt.NOT_FOUND):o.code==="no-available-slot"?new tr(`Failed to run test on ${s} - concurrency limit reached`):(ut.error("invalid code error response - get grid",{res:o}),new nt(bt.UNKNOWN))}function sg(r){return Kl(r)}async function ig(r,e,t){let i=(t||await sg(r)).find(n=>n._id===e);if(!i)throw new x(`Failed to find grid id: ${e}`);return yo(i)}async function gS(r,e,t){let i=(t||await sg(r)).find(n=>(n.name||"").toLowerCase()===e.toLowerCase());if(!i)throw new x(`Failed to find grid name: ${e}`);return yo(i)}async function Vl(r,e){let t=Ei[r];if(!t)return;let{slotId:s,gridId:i,browser:n,companyId:o,isSupportGrid:a}=t;if(delete Ei[r],!a){if(!s){ut.warn("failed to find grid slot id",{projectId:e});return}ut.info("release slot id",{projectId:e,companyId:o,slotId:s,gridId:i,browser:n});try{await Hl(o,e,s,i,n)}catch(c){ut.error("failed to release slot",{projectId:e,err:c})}}}async function hS(r){let e=Object.values(Ei).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid)try{await Gl(r,e)}catch(t){ut.error("failed to update grid keep alive",{err:t,slots:e,projectId:r})}}function yS(r){rg=global.setInterval(hS,1e4,r)}async function bS(r){let e=Object.keys(Ei);if(e.length){ut.warn("not all slots released before end runner flow",{projectId:r});try{await ne(e,t=>Vl(Number(t),r))}catch(t){ut.error("failed to release all slots",{err:t,projectId:r})}}}async function TS(r){await bS(r),clearInterval(rg)}function wS(r,e){let{testobjectSauce:t,saucelabs:s}=e;if(r==="testobject")return t.testobjectApiKey;if(r==="saucelabs")return s.accessKey}function vS(r,e){let{saucelabs:t}=e;if(r==="saucelabs")return t.username}function ng(r){let t=ho.isEmpty(r.testobjectSauce)?ho.isEmpty(r.saucelabs)?ho.isEmpty(r.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject",{host:s,port:i,path:n,protocol:o}=r,a=wS(t,r),c=vS(t,r);return{host:s,port:i,path:n,protocol:o,type:t,user:c,key:a,gridId:ce()}}async function og(r,e){let t=r.company.companyId;return await ig(t,e.gridId,r.allGrids)}async function ag(r){let{allGrids:e,company:t,host:s,useLocalChromeDriver:i,localTmaUrl:n,useChromeLauncher:o,gridId:a,grid:c}=r;if(i||o||n)return{mode:"local"};if(s)return ng(r);let l=t==null?void 0:t.companyId;if(a)return ig(l,a,e);if(c)return gS(l,c,e);if(ni(r)||r.tunnelOnlyMode){ut.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new nt("Missing host or grid configuration")}async function cg(r,e,t,s,i){let{host:n,project:o,grid:a,gridId:c,localTmaUrl:l,useLocalChromeDriver:d,useChromeLauncher:m,company:p}=t,f=!!(d||m||l),h=p==null?void 0:p.companyId;return fS(o,h,s,r,t,()=>ql({projectId:o,companyId:h,browser:r,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:n,testResultId:i}))}var ho,ut,Ei,tg,rg,mS,Ii,lg,ps=E(()=>{"use strict";ho=R(require("lodash"));fe();W();U();oe();Q();ut=A("grid-service"),Ei={},tg=/(^(https?):\/{2})?(.*)/,rg=null;mS=(r,e,t,s,i,n)=>{Ei[r]={gridId:t,companyId:e,slotId:s,browser:i,isSupportGrid:n}};Ii={start:yS,end:TS};lg=async(r={},e={},t={},s={},i={})=>{var g,b,T;let{company:{companyId:n}={},project:o}=r,{gridId:a,type:c}=e,l=r.browser||t.browserValue,d=!!r.tunnel,{maxRetries:m,currentRetry:p}=i;if(!a||!c||((c===N.TESTIM_LAMBDATEST||c===N.LAMBDATEST)&&await((g=s.enableIfNeeded)==null?void 0:g.call(s,e,n,o)),c!==N.HYBRID||!n||!l||!m||!p))return e;let f=await zl({companyId:n,gridId:a,maxRetries:m,currentRetry:p,browser:l,usingTunnel:d});ut.info("handling hybrid grid",{response:f,companyId:n});let h=yo({...e,...f.connectionDetails,provider:f.provider});return f.provider!=="lambdatest"&&((b=s.disable)==null||b.call(s)),f.provider==="lambdatest"&&await((T=s.enableIfNeeded)==null?void 0:T.call(s,h,n,o)),h}});function xi(){return bo||"master"}function ug(r="master",e="false"){if(typeof r!="string"&&(r!=null&&r.branch)&&r.branch==="master"){bo="master";return}if(r!=null&&r.isArchived)throw new x(`Branch ${r.branch} is archived, run aborted.`);if(r){bo=r.branch||r;return}bo=e?"master":void 0}var bo,Jl=E(()=>{"use strict";Q()});function Xl(r){return!r||r.length<=2?"anonymous":"AUID_"+(0,dg.createHash)("sha256").update(r).digest("hex")}var dg,mg=E(()=>{"use strict";dg=require("node:crypto")});function gg(r){if(!Me){if(r!=null&&r.userId?r={...r,userId:Xl(r.userId||"runnerId")}:r={anonymousId:"runnerId"},!vt){ns(Qr.CACHE_FN_NAME).then(e=>{vt=new To.Analytics({writeKey:e||fg,flushAt:1}),vt.identify(r)});return}vt.identify(r)}}function pt(r,e){return ds("ci",r,e)}function ds(r,e,t){if(Me)return;let s={userId:Xl(r||"runnerId")};if(!vt){ns(Qr.CACHE_FN_NAME).then(i=>{vt=new To.Analytics({writeKey:i||fg,flushAt:1}),vt==null||vt.track(Object.assign(s,{event:e,properties:t}))});return}vt.track(Object.assign(s,{event:e,properties:t}))}function hg(r){r&&(vt=new To.Analytics({writeKey:r,flushAt:1}),ct(async()=>r,Qr.CACHE_FN_NAME,Qr.TTL,{writeKey:r})())}var To,fg,vt,Ar=E(()=>{"use strict";ue();zt();To=require("@segment/analytics-node");oe();mg();fg="sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY"});var yg={};z(yg,{isCi:()=>ms});var ms,wo=E(()=>{"use strict";ms=!!(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID)});function Tg(r,e){return e!=null&&e.type&&(r[`${e.type}Mode`]=!0),r}function wg({executionId:r,projectId:e,testId:t,resultId:s,ucid:i,companyId:n,companyName:o,projectName:a,companyPlan:c,source:l,user:d,lightweightMode:m,isStartUp:p,projectType:f,appSource:h,gridType:g}){let b=Tg({executionId:r,projectId:e,testId:t,resultId:s,ucid:i,companyId:n,companyName:o,projectName:a,companyPlan:c,source:bg(l,d),isStartUp:p,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);pt("test-run-ci",b)}function vg({executionId:r,projectId:e,testId:t,resultId:s,result:i,ucid:n,companyId:o,companyName:a,projectName:c,companyPlan:l,source:d,user:m,lightweightMode:p,logger:f,isStartUp:h,projectType:g,appSource:b,gridType:T}){try{let v=Tg({executionId:r,projectId:e,testId:t,resultId:s,ucid:n,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:i.wasMockNetworkActivated,source:bg(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&b&&{appSource:b}},p);if(i.success){pt("test-run-ci-success",v);return}pt("test-run-ci-fail",{...v,failureReason:i.failureReason})}catch(v){f.error("failed to update test end analytics",{err:v})}}function Sg(r){pt("batch-run-ci",r)}var bg,Yl=E(()=>{"use strict";Ar();wo();bg=(r,e)=>r!=="cli"&&r!=="cli-local"?r:ms&&e?"ci-with-user":ms?"ci":e?"cli-with-user":r});var me,Ai,Ig=E(()=>{"use strict";me=class me{static colorString(e,t){return`${e}${t}${me.Reset}`}};me.Reset="\x1B[0m",me.Bright="\x1B[1m",me.Dim="\x1B[2m",me.Underscore="\x1B[4m",me.Blink="\x1B[5m",me.Reverse="\x1B[7m",me.Hidden="\x1B[8m",me.FgBlack="\x1B[30m",me.FgRed="\x1B[31m",me.FgGreen="\x1B[32m",me.FgYellow="\x1B[33m",me.FgBlue="\x1B[34m",me.FgMagenta="\x1B[35m",me.FgCyan="\x1B[36m",me.FgWhite="\x1B[37m",me.FgGray="\x1B[90m",me.BgBlack="\x1B[40m",me.BgRed="\x1B[41m",me.BgGreen="\x1B[42m",me.BgYellow="\x1B[43m",me.BgBlue="\x1B[44m",me.BgMagenta="\x1B[45m",me.BgCyan="\x1B[46m",me.BgWhite="\x1B[47m",me.BgGray="\x1B[100m";Ai=me});var Pi,Ql,SS,Zl,ES,vo,So,Eo,Io,Ro,xo=E(()=>{"use strict";U();oe();Pi=r=>{let{status:e,mobile:t}=r;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===ye.FAILED},Ql=r=>{let{status:e}=r;return e===ye.ABORTED},SS=r=>{let{status:e}=r;return e===ye.PASSED},Zl=r=>r.runnerStatus===ll.SKIPPED,ES=r=>r.testStatus===Qe.EVALUATING,vo=(r,e)=>Object.values(r).filter(t=>{var s,i;return Zl(t)&&(Ze(t,e)||((s=t.mobile)==null?void 0:s.isAppFromDevice)||((i=t.mobile)==null?void 0:i.isAppForIosVirtualDevice))}).length,So=r=>Object.values(r).filter(e=>Pi(e)&&ES(e)).length,Eo=r=>Object.values(r).filter(Pi),Io=r=>Object.values(r).filter(SS),Ro=r=>Object.values(r).filter(Ql)});function RS(r){let e=r.indexOf("--token");if(e!==-1)try{let t=r.slice();return t.splice(e,2),t}catch{}return r}var eu,Co,IS,Ao,Rg=E(()=>{"use strict";eu=R(require("lodash"));W();xo();Co=A("debug-reporter"),IS=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],Ao=class{constructor(e){this.options=e}onTestStarted(e,t){Co.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let s=this.options.gridData||{},i=s.provider,n=s.host,o=s.gridId,a=s.type,c=s.failedGetBrowserAttempts;Co.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:i,host:n,failedGetBrowserAttempts:c,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...eu.default.omit(this.options,IS),company:eu.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,s,i,n,o,a){let c=RS(process.argv);Co.info("Test Plan Started",{executionId:n,testPlanName:i,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,s,i,n){let o=Io(e).length,a=Object.keys(e).length-o;Co.info("Test Plan Finished",{executionId:i,testPlanName:t,isAnonymous:n,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:s})}}});var tu,Nt,ki=E(()=>{"use strict";oe();tu=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===N.DEVICE_FARM}},Nt=new tu});var su={};z(su,{Reporter:()=>xS});var or,Oi,Pr,Po,xg,ru,xS,iu=E(()=>{"use strict";or=R(require("chalk")),Oi=R(require("lodash"));U();oe();ki();xo();Pr={success:or.default.green,warn:or.default.yellow,error:or.default.red},{CLI_MODE:Po}=Ht,xg="device",ru=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 s=`(${e.testId})`,i=`url: ${or.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${s} ${i}`.trim())}onTestFinished(e,t){let s=e.success?ye.PASSED:ye.FAILED,i=`(${e.testId})`,n=Pr[e.success?"success":"error"];console.log(n(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${s} ${i} duration: ${Hn(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(s=>{let i=qe(this.options.editorUrl,this.options.project,s.testId,s.resultId,this.branchToUse);return`${s.name} : ${i}`});console.log(Pr.error("Failed runs are:")),console.log(Pr.error(t.join(`
|
|
18
|
-
\r`)))}onTestPlanFinished(e,t,s,i,n){let o=Eo(e),a=Io(e),c=Ro(e),l=a.length,d=c.length,m=o.length,p="",f="";if(Nt.isTestStatusEnabled){let v=So(e);p=` FAILED-EVALUATING: ${v}`,m-=v,f=` SKIPPED: ${vo(e,this.options)}`}let h=this.buildTestPlanName(n,t),g,b=Pr[m?"error":"success"],T=`PASSED: ${l} FAILED: ${m}${p} ABORTED: ${d}${f} Duration: ${Hn(s)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${i})`:g=`Test plan${h} completed ${T} (${i})`,this.printWorkerDivider(),console.log(b(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let s=Oi.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,i=Oi.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,n=Oi.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Oi.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[n,i,s,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,s,i,n,o,a){let c=p=>{p.forEach((f,h)=>{var v;let g=(v=f.testData)!=null&&v.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",b=`(${f.testId})`,T="";f.testOptimization?T=` [${f.testOptimization.reason}]`:Ze(f,this.options)&&(T="-quarantine"),console.log(" ",h+1,":",`${f.name}${T}`,b,g)})},l=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,i)} test plan with ${m} (${n})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),s.length>0&&(console.log("After all:"),c(s)),this.printWorkerDivider()}onGetSlot(e,t){let s=this.options.grid||this.options.gridId,i=this.options.mode===Po.APPIUM?xg:t;s&&console.log(this.toWorkerIdPrefix(e),`Get ${or.default.underline(i)} slot from ${or.default.underline(s)}`)}onGetSession(e,t,s){let i=s===Po.APPIUM?xg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${i} to run ${or.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,s){if(s!==2)return;let i=this.options.grid||this.options.gridId,n=this.options.mode===Po.APPIUM?"device":"browser";if(i)console.log(Pr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${n} from the grid ${i}`));else if(this.options.useLocalChromeDriver)console.log(Pr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===Po.APPIUM?"Appium":"Selenium";console.log(Pr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},xS=ru});var au={};z(au,{Reporter:()=>_S});function CS(r){let e=r.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${r.name}${t}`}function AS(r){return r.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${r.visitedUrlsList||""}`}function PS(r){return`${r.visitedUrlsJson||""}`}async function kS(r,e,t,s,i,n){function o(p){let f=qe(r,t,p.testId,p.resultId,s),h={$:{name:CS(p),classname:i,time:yl(p.duration),ownedBy:p.testOwnerName,ownerEmail:p.testOwnerEmail},"system-out":f};if(Pi(p)||Ql(p)){let g=`Step Failed: ${p.failureReason||p.reason}`,b=Pi(p)?`${g} More info at: ${f}`:g;h.failure={$:{message:b}}}return Zl(p)&&Ze(p,n)&&Nt.isTestStatusEnabled&&(h.skipped={}),n.urls&&(h["visited-urls-list"]=AS(p),h["visited-urls-json"]=PS(p)),h}function a(p){let{results:f,testPlanName:h,configName:g}=p,b=f||{},v={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(b),failures:d(b),timestamp:c(e)};if(Nt.isTestStatusEnabled){v.skipped=vo(b,n);let y=So(b);v.failures-=y,v["failure-evaluating"]=y}return{$:v,testcase:Object.keys(b).map(y=>o(b[y]))}}function c(p){let f=Object.keys(p).map(g=>p[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function l(p){return Object.keys(p).length}function d(p){return Eo(p).length+Ro(p).length}let m={testsuites:{testsuite:e.map(p=>a(p))}};try{return new ou.Builder().buildObject(m)}catch(p){return OS(p)}}function OS(r){let e=new ou.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:r.message}}}}}};return e.buildObject(t)}var ou,Cg,nu,_S,cu=E(()=>{"use strict";ou=R(require("xml2js"));U();Cg=require("fs");ki();xo();nu=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,s=this.options.project,i=await kS(this.options.editorUrl,e,s,this.branchToUse,this.classname,this.options);if(t)try{return await Cg.promises.writeFile(t,i),console.log("JUnit XML file saved to",t),e}catch(n){return console.error("could not save report file",t,n),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};_S=nu});var Ag={};z(Ag,{Reporter:()=>LS});function fs(r){return r?r.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 lu,uu,LS,Pg=E(()=>{"use strict";W();lu=A("team-city-reporter");uu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},s=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",i=`${e.name} (${e.testId})${s}`;return fs(i)}onTestStarted(e,t,s,i){if(s){lu.debug("skip report test started because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testStarted name='${n}' captureStandardOutput='true' flowId='${i}']`)}onTestFailed(e,t,s,i,n,o){if(n){lu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${fs(t)}' details='${fs(s)}' flowId='${o}']`)}onTestFinished(e,t,s){if(s){lu.debug("skip report test finished because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testFinished name='${i}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,s="ignore"){let i=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${i}' message='${fs(s)}']`)}onTestPlanStarted(e,t,s,i){console.log(`##teamcity[testSuiteStarted name='${fs(i)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${fs(t)}']`)}},LS=uu});var kg={};z(kg,{Reporter:()=>DS});var pu,DS,Og=E(()=>{"use strict";pu=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,s,i,n){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:n}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},DS=pu});function Oo(r){let{platform:e}=process;e==="win32"?(0,ko.exec)(`start chrome ${r}`):e==="darwin"?(0,ko.exec)(`open -a "Google Chrome" ${r}`):e==="linux"&&(0,ko.exec)(`google-chrome ${r}`)}var ko,du=E(()=>{"use strict";ko=require("child_process")});var _g={};z(_g,{Reporter:()=>NS});var mu,NS,Lg=E(()=>{"use strict";U();du();mu=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 Oo(t)}},NS=mu});var fu,te,Mt=E(()=>{"use strict";Rg();fu=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 s=e.reporters;if(this.reporters.push(new Ao(e)),s===void 0||s.length===0){let{Reporter:i}=await Promise.resolve().then(()=>(iu(),su));if(this.reporters.push(new i(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:n}=await Promise.resolve().then(()=>(cu(),au));this.reporters.push(new n(e,t))}}else(await Promise.all([s.includes("teamcity")&&Promise.resolve().then(()=>(Pg(),Ag)),s.includes("console")&&Promise.resolve().then(()=>(iu(),su)),s.includes("junit")&&Promise.resolve().then(()=>(cu(),au)),s.includes("json")&&Promise.resolve().then(()=>(Og(),kg)),s.includes("chrome")&&Promise.resolve().then(()=>(Lg(),_g))])).forEach(n=>{n&&this.reporters.push(new n.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,s,i,n){let o={};o=e;let a=Date.now()-(s||0);return[o,t,a,i,n]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...s)=>{var n;let i=t==null?void 0:t(...s);for(let o of this.reporters)await((n=o[e])==null?void 0:n.call(o,...i||s))}}},te=new fu});async function gu(r,e,t){let s=gs[r];if(!s)return;let{slotId:i}=s;if(delete gs[r],!i){St.warn("failed to find slot slot id",{companyId:e,workerId:r});return}St.info("release slot id",{companyId:e,slotId:i});try{await yu(e,t,i)}catch(n){St.error("failed to release slot",{companyId:e,err:n})}}async function MS(r,e){let t=Object.values(gs).filter(Boolean);if(t.length!==0)try{await Tu(r,e,t)}catch(s){St.error("failed to update slot keep alive",{err:s,slots:t,companyId:r})}}function FS(r,e){Dg=global.setInterval(()=>MS(r,e),1e4)}async function US(r,e){let t=Object.keys(gs);if(t.length){St.warn("not all slots released before end runner flow",{companyId:r});try{await ne(t,s=>gu(Number(s),r,e))}catch(s){St.error("failed to release all slots",{err:s,companyId:r})}}}async function BS(r,e){await US(r,e),clearInterval(Dg)}async function Mg(r,e,t){let s;try{s=await hu(r,e)}catch(i){throw St.error("failed to get slot",{companyId:r,err:i}),new Error(bt.UNKNOWN)}if(St.info("get slot info",{...s,companyId:r}),!s||!["success","error"].includes(s.status))throw St.error("invalid response - get slot",{res:s}),new Error(bt.UNKNOWN);if(s.status==="success")return Ng(t,{slotId:s.slotId}),s.slotId;throw s.code==="not-found"?new nt(bt.NOT_FOUND):s.code==="no-available-slot"?new tr("Failed to run test - concurrency limit reached"):(St.error("invalid code error response - get slot",{res:s}),new nt(bt.UNKNOWN))}async function Fg(r,e,t,s){let i=gs[s];if(!i)throw new Error("slot not found");Object.assign(i,t),Ng(s,i),await bu(r,e,i),St.info("update slot data on server",{companyId:r,projectId:e,slotData:t})}var St,gs,Dg,Ng,_i,hs=E(()=>{"use strict";fe();W();U();oe();Q();St=A("slot-service"),gs={},Dg=null,Ng=(r,e)=>{gs[r]=e};_i={start:FS,end:BS}});function Bg(r,e=process){async function t(s){await ae(ne(Ug,async i=>i()),1e4).catch(()=>null),r(s)}e.on("uncaughtException",async s=>{s.message.includes("Command browsingContext")||(Di.error("Caught exception",{err:s}),console.log("Uncaught exception"),s.message&&console.log("Message =",s.message),s.reason&&console.log("Reason =",s.reason),await t(s))}),e.on("unhandledRejection",s=>{var i;if(Di.fatal("Caught unhandled promise rejection",s),!((i=s==null?void 0:s.message)!=null&&i.includes("ENOTFOUND x-api.rollout.io")))throw s}),e.on("rejectionHandled",()=>{Di.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let s="Runner aborted - SIGTERM event",i=new Error(s);throw Di.error(s),t(i),i}),e.once("SIGINT",()=>{let s="Runner aborted - SIGINT event",i=new Error(s);throw Di.error(s),t(i),i}),e.once("exit",s=>{r(s)})}function ys(r){Ug.push(r)}var Di,Ug,Ni=E(()=>{"use strict";W();U();Di=A("process-handler"),Ug=[]});var Vg={};z(Vg,{installAllLazyDependencies:()=>VS,lazyRequire:()=>dt});async function dt(r,e={}){let t=Cl(r);if(t)return t;let s;e.silent||(s=(0,jg.default)(`Installing ${r} before first usage...`).start());try{let i=await WS(r);return s&&s.succeed(),i}catch(i){$S.warn("failed to install dependency lazily",{dependency:r,err:i});let n=Wg(r),o=`${r}@${n}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${r} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${o}`;throw s&&s.fail(l),i}}async function WS(r){return bs.has(r)||(bs.set(r,$g(r)),bs.get(r).catch(()=>{bs.delete(r)})),bs.get(r)}async function $g(r){let e=Cl(r);if(e)return e;let t=Wg(r),s=`${r}@${t}`;return await no(yt(),s),nr(r)}async function VS(){let r=Object.keys(Pc);for(let e of r)await $g(e)}function Wg(r){let e=Object.entries(Pc).find(([t])=>t===r);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var jg,$S,bs,Mi=E(()=>{"use strict";jg=R(require("ora"));ls();W();U();kn();pi();$S=A("lazy-require"),bs=new Map});var Gg,_o,Hg=E(()=>{"use strict";Gg=require("istanbul-lib-report"),_o=class extends Gg.ReportBase{constructor(e){super(),e||={},this.appendToObject=e.appendToObject||{}}onStart(e){let t=e.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,t.toJSON())}}});var zg,qg,Kg,Fi,Et,Jg,Lo,wu,Xg,GS,Yg,Qg,HS,zS,Zg,qS,KS,JS,XS,YS,eh,th=E(()=>{"use strict";zg=R(require("ora")),qg=R(require("dayjs")),Kg=R(require("test-exclude")),Fi=R(require("fs")),Et=R(require("path")),Jg=R(require("istanbul-reports")),Lo=R(require("istanbul-lib-report"));fe();Q();U();W();Mi();Hg();wu=A("test-run-status"),Xg=r=>{try{return new URL(r)}catch{try{return new URL(`file://${r}`)}catch{return{}}}},GS=r=>!!Xg(r).search,Yg=r=>r?Xg(r).pathname.substring(1):"",Qg=(r,e)=>{let t=Yg(e);return!new Kg.default({relativePath:!1,include:r}).shouldInstrument(t)},HS=r=>r.substring(0,r.indexOf("?")),zS=async({source:r,sourceMapDir:e,sourceMapType:t})=>{let s=await dt("convert-source-map");if(t==="file"&&!e)throw new x("--code-coverage-source-map-path [path]");return e?s.fromMapFileSource(r,e):s.fromSource(r)},Zg=(r,e)=>`${Et.resolve(r,Yg(e))}.js`,qS=async(r,e,t)=>{let{codeCoverageInclude:s}=r;await ne(Object.values(t),async i=>{if(!i)return;let n=i.toObject();await ne(n.sources,async(o,a)=>{if(Qg(s,o))return;let c=Zg(e,o);await Fi.promises.mkdir(Et.parse(c).dir,{recursive:!0}),await Fi.promises.writeFile(c,n.sourcesContent[a])})})},KS={getPath(r){if(typeof r=="string")return r;let e=r.getQualifiedName();return r.isSummary()?e!==""?e+="/index.html":e="index.html":(GS(e)&&(e=HS(e)),e+=".html"),e},relativePath(r,e){let t=this.getPath(e),s=Et.dirname(this.getPath(r));return Et.posix.relative(s,t)},assetPath(r,e){return this.relativePath(this.getPath(r),e)}},JS=async(r,e,t,s)=>{let{codeCoverageReporter:i}=r,n={},o=Lo.createContext({dir:t,coverageMap:e,watermarks:Lo.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Zg(s,a);return Fi.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new _o({appendToObject:n}).execute(o),Array.isArray(i)&&i.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:KS}),Jg.create(a,c).execute(o)}),n},XS=async(r,{source:e,sourceMap:t,functions:s})=>{let{codeCoverageInclude:i}=r;if(!t||t.sourcemap.sources.length===0)return;let o=(await dt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Qg(i,a));return await o.load(),o.applyCoverage(s),o.toIstanbul()},YS=async(r,e)=>{let{mergeProcessCovs:s}=await dt("@bcoe/v8-coverage"),i={result:[]},n=new Map,a=(await Su(r,"testResult",`runId=${e}`)).data.docs;return await ne(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Ui(c,9e4);await ne(l,async d=>{if(!n.has(d.url)){let m=d.text;d.sourceUrl&&(n.set(d.url,"TEMP"),m=await vu(d.sourceUrl)),n.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,i=s([i,{result:[d]}])})},{concurrency:20}),{covUrlMap:n,mergedCoverages:i}},eh=async(r,e,t,s)=>{if(!r.collectCodeCoverage)return;wu.info("start js coverage process");let i=(0,zg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),n=Et.resolve(r.codeCoverageReportPath||"./coverage"),o=Et.resolve(n,`.js/${(0,qg.default)().format("DDMMYYYYHHmmss")}`),a=r.codeCoverageSourceMapPath?Et.resolve(r.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([dt("istanbul-lib-coverage"),YS(r.project,s)]);if(l.result.length===0){i.fail("Failed to report coverage information - js code coverage is empty");return}wu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),p={};await ne(l.result,async({url:h,functions:g})=>{let{text:b,sourceMapType:T}=d.get(h),v=await zS({sourceMapType:T,source:b,sourceMapDir:a});p[h]=v;let y=await XS(r,{source:b,sourceMap:v,functions:g});m.merge(y)}),await qS(r,o,p);let f=await JS(r,m,n,o);return i.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof x?i.fail(`${l}, missing arg: ${c.message}`):i.fail(l),wu.error(l,{err:c})}}});var rh={};z(rh,{SELENIUM_PERF_MARKS:()=>ke,SeleniumPerfStats:()=>kr});var ke,QS,kr,Ts=E(()=>{"use strict";U();ke={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},QS=["ALL",...Object.values(ke)],kr=class{constructor(){this.marks=Object.fromEntries(QS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=ce();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let s=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(s);return}this.marks[t].push(s)}getStats(){let e=Object.entries(this.marks).flatMap(([t,s])=>!Array.isArray(s)||!s.length?[]:[[`${t}_COUNT`,s.length],[`${t}_P50`,Jn(s,50)],[`${t}_P95`,Jn(s,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var oh={};z(oh,{initServer:()=>tE,mapFilesToLocalDrive:()=>Iu});function Iu(r,e){try{r.failurePath=(r.failurePath||[]).map(t=>Object.assign(t,Do[t.id]?{screenshot:Do[t.id]}:{})),Object.keys(No).forEach(t=>{r.assets||={},r.assets[nh[t]]=No[t]}),r.assets||={},r.assets.screenshots=Object.values(Do)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),r.failurePath||=[],r.assets||={},r.assets.screenshots||=[]}}async function tE({agentPort:r,agentBind:e,saveRCALocally:t}){let s=await dt("multer"),i=typeof t=="string"?t:ZS;await Eu.promises.mkdir(i,{recursive:!0});let n=s({storage:s.diskStorage({async destination(c,l,d){let m=JSON.parse(c.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let p=Bi.join(i,m.testResultId);try{await Eu.promises.mkdir(p,{recursive:!0})}catch(f){return d(f,"")}return d(null,p)},filename(c,l,d){let{fileName:m}=c.body,p=JSON.parse(c.body.metadata||"{}");if(!p.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(p.stepId){let f=Bi.extname(m);return d(null,`step_${p.stepId}_${p.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,ih.default)();o.disable("x-powered-by"),o.post("/",n.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(Do[d.stepId]=c.file.path),d.testResultId&&eE.includes(d.subType)&&(No[d.subType]||=[],No[d.subType].push(c.file.path)),l.sendStatus(200)}),o.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let d=a(o);d.listen(r,e),d.on("error",m),d.on("listening",()=>c(d.address()));function m(p){if(p.syscall!=="listen")return l(p);switch(p.code){case"EACCES":case"EPERM":return l(new x(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return l(new x(`Port ${r} is already in use`));default:return l(p)}}})}var Eu,sh,Bi,ih,ZS,Do,No,nh,eE,Ru=E(()=>{"use strict";Eu=R(require("fs")),sh=R(require("os")),Bi=R(require("path")),ih=R(require("express"));Q();Mi();ZS=Bi.join(sh.tmpdir(),"testim/rca/"),Do={},No={},nh={"test-log":"consoleLogs","har-file":"networkLogs"},eE=Object.keys(nh)});var ar,xu,ji,ah=E(()=>{"use strict";ar=R(require("lodash"));U();W();xu=A("override-test-data-builder"),ji=class{constructor(e,t,s){this.params=e;this.testInfoList=t;this.projectId=s}isObjectNotArray(e){return ar.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(e=!1){let{params:t,projectId:s}=this;return this.isObjectNotArray(t)&&t.overrideTestData!==void 0&&(this.isObjectNotArray(t.overrideTestData)&&!ar.isEmpty(t.overrideTestData)?(Object.keys(t.overrideTestData).forEach(i=>this.overrideSingleTest(i,t.overrideTestData[i])),delete t.overrideTestData):xu.error("invalid overrideTestData",{overrideTestData:t.overrideTestData,projectId:s})),this.isObjectNotArray(t)&&t.overrideAllTestsData!==void 0&&(ar.isObject(t.overrideAllTestsData)&&!ar.isEmpty(t.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,t.overrideAllTestsData)),delete t.overrideAllTestsData):xu.error("invalid overrideAllTestsData",{overrideAllTestsData:t.overrideAllTestsData,projectId:s})),this.isArrayOfObjects(t)&&e&&this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,t)),this.testInfoList}overrideSingleTest(e,t){let{projectId:s}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}xu.error("skip override test data to test name",{testName:e,projectId:s}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let s=this.mapTestListToUniqueId(e);if(s.length!==0)return this.createNewTestPerOverrideTestData(s,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return ar.chain(t).map(s=>{if(s.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(s)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:s}=this;return[...new Set(e)].map(i=>{let n=s.map(d=>this.generateTestUniqId(d)),o=n.indexOf(i),a=n.lastIndexOf(i),c=s[o],l=this.createNewTestItems(c,t);return s.splice(o,a-o+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((s,i)=>{let n=ce();return{...e,resultId:n,testData:{value:s,index:i+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function $i(r,...e){if(!(!r||typeof r!="function"))try{return await r(...e)||{}}catch(t){throw et.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var cr,et,rE,sE,iE,nE,Mo,ch=E(()=>{"use strict";cr=R(require("lodash"));U();oe();ps();hs();fe();Q();W();Mt();Ni();th();Ts();Ru();ue();pe();ah();ki();et=A("test-run-status"),rE=Er(),sE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,iE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,nE=it();Mo=class{constructor(e,t,s,i){this.testInfoList=e;this.options=t;this.branchToUse=i;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.userTestDataParams={};this.seleniumPerfStats=new kr;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData,this.userTestDataString=this.options.testDataString;let n=ii(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:Ln||t.parallel||1,browser:n,gitBranch:rE,gitCommit:sE,gitRepoUrl:iE,runnerVersion:nE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:i,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:s,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:s,projectId:i,executionId:n,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:d,testStatus:m,testCreatorName:p,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:b,testSuites:T,allLabels:v}=a,y={originalTestResultId:t,previousTestResultId:s,config:cr.cloneDeep(c),testId:l,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...y,testCreatorName:p,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:b,testSuites:T,allLabels:v},Pu({projectId:i,runId:n,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:s,testResult:y})}testStart(e,t,s,i){let n=this.getTestResult(s);return n.workerId=e,te.onTestStarted(n,e,i,s),n}async updateTestStatusRunning(e,t,s){var l;let{project:i,remoteRunId:n,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Uo(i,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){et.error("failed to upload test data artifact (runner)",{err:d})}let c=cr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,Or(i,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:n,testRetryKey:s})}async testStartReport(e,t,s){var n;if(Ze(e,this.options))return;let i=this.exportsGlobal;try{let o=await $i(this.options.beforeTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token),a=Array.isArray(this.userTestDataParams)?{}:this.userTestDataParams||{},c=(n=e.config)!=null&&n.testDataPrioritized?e.config.testData:{};return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...a,...c,...this.beforeSuiteParams,...o},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,s),e}catch(o){throw et.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,s,i,n){let o=this.testStart(e,t,s,i);return this.testStartReport(o,t,n)}onGridSlot(e,t){let s=this.getTestResult(e);s.config.gridInfo={...t,key:void 0,user:void 0},et.info("on get grid info",{gridInfo:s.config.gridInfo})}reportTestStatus(e,t,s,i){let{name:n,testId:o,testStatus:a}=s,{resultId:c,success:l}=t;if(a===Qe.EVALUATING&&Nt.isTestStatusEnabled){te.onTestIgnored(e,s,`test in ${Qe.EVALUATING} status`);return}if(l){te.onTestPassed(n);return}te.onTestFailed(s,s.failureReason,qe(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,i,c)}calcResultText(e){return e.success?ye.PASSED:ye.FAILED}onTestIgnored(e,t){let s=this.getTestResult(t);te.onTestIgnored(e,s,`test in ${Qe.QUARANTINE}`)}monitorMemoryUsage(e){let t=bl();t.isOverThreshold&&et.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,s,i,n){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=i,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&Iu(o,et),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,n),this.monitorMemoryUsage(o),te.onTestFinished(o,e,n);let c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,s,i){var o;let n=s.exportsGlobal;try{try{await $i(this.options.afterTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token)}catch(a){et.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 Or(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:s.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...i},5)}catch(a){throw et.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,s,i,n,o){let a=this.testEnd(e,t,s,i,n);return this.testEndReport(a,s,t,o)}getMobileRunSkippedReason(e,t,s){let i="",{APP_FROM_DEVICE:n,VIRTUAL_BUILD:o}=dl;return e&&(i=n),Zr(t,s)&&(i=o),i}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,s=e.company.companyId,i=(o=e.gridData)==null?void 0:o.type,n=t.map(a=>{var f,h,g,b;let c=e.browser?ai(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=es(O,i)&&oi(a.nativeApp)&&!e.appId,d=sr(e)&&(Zr(a.nativeApp,i)||l),m=Ze(a,e)||d,p={testId:a.testId,testOptimization:a.testOptimization,status:m?ye.SKIPPED:ye.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Qe.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,i)},config:{...this.execConfig,companyId:s,testData:((f=a.testData)==null?void 0:f.value)||null,testDataPrioritized:((h=a.testData)==null?void 0:h.prioritize)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((g=a.testData)==null?void 0:g.total)||null,testDataIndex:((b=a.testData)==null?void 0:b.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:c.browserValue.toLowerCase()}};return[a.resultId,p]});return Object.fromEntries(n)}async endKeepAlive(e,t,s){e==="redis"&&await _i.end(s,t),e==="mongo"&&await Ii.end(t)}async executionStart(e,t,s,i,n){et.info("execution started",{executionId:e,gridId:this.execConfig.gridId,gridHost:this.execConfig.gridHost,gridName:this.execConfig.gridName,gridType:this.execConfig.gridType,parallel:this.execConfig.parallel,runnerVersion:this.execConfig.runnerVersion,source:this.execConfig.source});let{options:o}=this,{remoteRunId:a,projectData:c,company:{companyId:l}={},slotService:d}=o;ys(()=>Promise.all([this.endKeepAlive(d,t,l),Fo("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=s||Date.now();let m={projectId:t,executionId:e,...O.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:n}},p=this.userTestDataString,f=await $i(new Function(p||""));if(f&&(this.userTestDataParams=f,Array.isArray(f))){let S=new ji(f,cr.cloneDeep(this.testInfoList),t);this.testInfoList=S.overrideTestData(!0)}let h=await $i(o.beforeSuite,m),g=new ji(h,cr.cloneDeep(this.testInfoList),t);this.testInfoList=g.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=h;let{testInfoList:b}=this,T=[],v=[],y=[];for(let S of b){if(S.isBeforeTestPlan){T.push(S);continue}if(S.isAfterTestPlan){y.push(S);continue}v.push(S)}let w=async()=>{let S=cr.cloneDeep(this.testRunStatus);await ne(Object.keys(S),async B=>{var j;let V=S[B],I=(j=V.config)==null?void 0:j.testData,k=V.testId,L=await Uo(t,k,B,I,c.defaults);L&&(delete V.config.testData,V.config.testDataUrl=L)});let C=!!(o.useLocalChromeDriver||o.useChromeLauncher),_=Au({executionId:e,projectId:t,labels:i||[],startTime:s,executions:S,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:C,intersections:o.intersections});return this.executionStartedPromise=_,_.catch(B=>et.error(B)),_};try{await w()}catch(S){et.error("Failed to start suite",{err:S}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:T,tests:v,afterTests:y}}concatSeleniumPerfMarks(e){cr.chain(e).keys().each(t=>{let s=t;this.seleniumPerfStats.marks[s]&&(this.seleniumPerfStats.marks[s]=[...this.seleniumPerfStats.marks[s],...e[s]])}).value()}async executionEnd(e){var d;let t=El(this.testRunStatus),s=t.length,i=0,n=0,o=0;for(let{status:m,testStatus:p}of t)m===ye.PASSED&&i++,m===ye.SKIPPED&&n++,m===ye.FAILED&&p===Qe.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await $i(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:s,passed:i,skipped:n})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),et.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await eh(this.options,this.branchToUse,s,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Fo("FINISHED",e,this.options.project,s===i+n+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw et.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,s,i){let n=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await Cu(e,["QUEUED"],t,s,i,this.startTime,null,this.options.project);for(let o of n){let a=this.getTestResult(o);a.status=t,a.failureReason=s,a.success=i}return this.testRunStatus}}});function ku(r){var n;let e=r.canary?"-master.zip":".zip",t=`${Zt}/testim-headless${e}`,s=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(n=r.company)==null?void 0:n.companyId,projectId:r.project,runnerEnvironment:zs});return s||(oE.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:r.resultId,executionId:r.executionId,projectId:r.project}),s=`${Zt}/testim-headless.zip`),!(r.ext||r.extensionPath)&&s&&(t=s,r.testimHeadlessExtensionDownloadUrl=s),{chrome:t,"edge-chromium":t}}function lh(r){let{chrome:e}=ku(r);return e}function Bo(r){let e=`${Zt}/sessionPlayer`;return r.canary?`${e}-master`:e}var oE,Wi=E(()=>{"use strict";ue();pe();W();oE=A("runOptionsUtils")});function ws(r){var i;let t=(i=new RegExp(`^\\b(${Object.values(Ou).join("|")})`).exec(r))==null?void 0:i[0];return t||Ou[em]||"usw2"}var Ou,ph,jo=E(()=>{"use strict";ue();Ou={"us-west-2":"usw2","eu-central-1":"euc1"},ph=Object.fromEntries(Object.entries(Ou).map(([r,e])=>[e,r]))});function dh(r,e){if(e){if(!dE.has(e)){Vi.warn(`OS ${e} is not supported by LT`,{testResultId:r});return}return e}}var mh,fh,qt,gh,hh,yh,$o,bh,Vi,aE,cE,Gi,lE,uE,pE,Kt,dE,Wo=E(()=>{"use strict";mh=R(require("ms")),fh=R(require("p-retry")),qt=R(require("node:os")),gh=R(require("portfinder")),hh=R(require("node:child_process"));U();We();fe();yh=R(require("node:fs")),$o=R(require("node:fs/promises")),bh=require("node:path");Q();W();Wi();oe();pe();U();jo();Vi=A("lambdatestService"),aE="https://downloads.lambdatest.com/tunnel/v3",cE={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"},Gi=`${qt.tmpdir()}/LT`,lE=`${Gi}/LT`,uE=(0,mh.default)("15m"),pE="2560x1440",Kt=class r{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===N.TESTIM_LAMBDATEST||e.type===N.LAMBDATEST||e.type===N.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t,s){if(r.isLambdatestGrid(e)&&(r.lambdatestConfigPromise||=_u(t,s),r.lambdatestConfig=await r.lambdatestConfigPromise,this.isActive=!0,s))try{let i=await Promise.resolve().then(()=>(fe(),we));this.smartUIIntegrationData=await i.getVisualTestingIntegrationData(s,"lambdatest")}catch{}}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?uE:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await Te(lE))return;let t=cE[qt.platform()+qt.arch()];if(!t)throw new Error(`tunnel on ${qt.platform()+qt.arch()} platform is not supported.`);let s=`${Gi}.zip`;await Xe(`${aE}/${t}`,s),await Ye(s,Gi)}static async chmodLtTunnel(e){if(!(qt.platform()==="win32"||!await Te(e))){try{await $o.access(e,yh.constants.X_OK);return}catch{}try{await $o.chmod(e,"777")}catch(s){throw Vi.error("Failed to make LT tunnel executable",{e:s}),s}}}static async delay(e){await ie(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){r.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await gh.getPortPromise(),{gridData:s={},gridUsername:i,gridPassword:n,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;r.tunnelName=ce();let l=["--tunnelName",r.tunnelName,"--infoAPIPort",String(t)];if(O.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],o&&a)l=[...l,"--ntlm-username",o,"--ntlm-password",a];else{let p=JSON.parse(O.flags.addCustomLTtunnelNTLMOptions.getValue());p&&(l=[...l,...hl(p)])}if(O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,*.betterstackdata.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),s.tunnelUser&&s.tunnelKey)l=[...l,"--user",s.tunnelUser,"--key",s.tunnelKey];else if(i&&n)l=[...l,"--user",i,"--key",n];else throw new x("tunnel requires username and password");if(c)try{let p=new URL(c);l=[...l,"--proxy-host",p.hostname],p.port&&(l=[...l,"--proxy-port",p.port]),p.username&&p.password&&(l=[...l,"--proxy-user",p.username,"--proxy-pass",p.password])}catch{throw new x("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await r.delay(3e3),await r.chmodLtTunnel((0,bh.join)(Gi,"LT")),r.tunnel=hh.spawn("./LT",l,{cwd:Gi});let d="",m="";r.tunnel.stdout.on("data",p=>{d+=p.toString()}),r.tunnel.stderr.on("data",p=>{m+=p.toString()});try{let p=await(0,fh.default)(()=>Ee(`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});Vi.info("LT tunnel info",p)}catch(p){throw Object.assign(p,{stdoutResult:d,stderrResult:m}),Vi.error("Failed to start LT tunnel",{err:p}),p}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!r.tunnel))return new Promise((t,s)=>{r.tunnel.on("close",i=>{i&&s(new Error(`tunnel process exited with code ${i}`)),t()}),r.tunnel.kill()})}getCapabilities(e,t,s,i,n,o,a,c){var _,B;if(!this.isActive)return{};let l=r.lambdatestConfig.CAPABILITIES[t]||{},d={...r.tunnelName&&{tunnel:!0,tunnelName:r.tunnelName}},m=[],{canary:p,ext:f,extensionPath:h,installCustomExtension:g}=e,b={platform:dh(i,a==null?void 0:a.os)||dh(i,(_=o==null?void 0:o.lt)==null?void 0:_.platform)||l.platform||r.lambdatestConfig.PLATFORM,resolution:r.lambdatestConfig.RESOLUTION??pE,...t!=="safari"&&{version:l.version}};if(c!==J.APPIUM&&c!==J.SELENIUM&&!f){let V=ku({canary:p});!h&&V[t]&&(m=[...m,V[t]]),h&&De(h)&&(m=[...m,h]),!m.length&&!h&&Vi.warn("No extension was loaded in LambdaTestService",{extUrls:V,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&De(g)&&(m=[...m,g]);let T=ws(e.project||""),y={euc1:"eu"}[T],w=y?{region:y}:{},S=(B=this.smartUIIntegrationData)!=null&&B.projectToken?{smartUI:{project:this.smartUIIntegrationData.projectToken,build:s}}:{};return{"LT:Options":{build:s,name:`${i} - ${n}`,...w,selenium_version:r.lambdatestConfig.SELENIUM_VERSION,timezone:r.lambdatestConfig.TIMEZONE,...l,...b,loadExtension:m,...d,...S,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}},dE=new Set(["Linux","Windows 10","Windows 11","MacOS Tahoe","MacOS Sequoia","macOS Sonoma","macOS Ventura","macOS Monterey","macOS Catalina","macOS Big Sur","macOS Mojave","macOS High Sierra","macOS Sierra","OS X El Capitan","OS X Yosemite","OS X Mountain Lion"])});var Th,mE,Vo,Lu=E(()=>{"use strict";Q();Th=["platformName","platform","app","bundleId","appPackage","extensions"],mE=["selenium_version","protocol","host","port","path","build"],Vo=(r,e)=>{let t=e==="lambdaTest"?[...Th,...mE]:Th,s=[],i=[r];for(;i.length;){let n=i.pop();for(let[o,a]of Object.entries(n))t.includes(o)&&s.push(o),a&&typeof a=="object"&&i.push(a)}if(s.length)throw new x(`Custom capabilities contains forbidden keys: ${s.join(", ")}`)}});function gE(r,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(r.desiredCapabilities,t),r}function kh(r){return Rh.readFileSync(r,{encoding:"base64"})}function Oh(r,e,t,s){if(t!=null&&t.isLambdatestRun()&&De(r))return null;if(r){if(s)return r.endsWith(".zip")?(Ye(r,Sh),Sh):r;let i=kh(r);Ss.info(`adding extension: custom, path: ${r} length: ${i.length} hash: ${Mu(i)} current extension count: ${e.length}`),e.push(i)}return null}function _h(r,e,t,s,i,n){if(i!=null&&i.isLambdatestRun())return null;let o=r.testimHeadlessExtensionDownloadUrl;if((r.ext||s)&&!o){let m=typeof r.ext=="string"?r.ext:`${__dirname}/..`,p=s||m,f=`--load-extension=${p}`;return Ss.info(`adding extension: testim unpacked , path: ${p}`),t.push(f),null}let c=`testim-headless${r.canary?"-master.zip":".zip"}`;!r.extensionPath&&o&&(c=_r.basename(o));let l=_r.join(process.cwd(),c);if(n)return Ye(l,vh),vh;let d=kh(l);return Ss.info(`adding extension: testim zipped, path: ${l} length: ${d.length} hash: ${Mu(d)} current extension count: ${e.length}`),e.push(d),null}function hE(r,e,t,s,i,n,o,a){var g,b;let c=t.seleniumName||t.browserValue,l=[],d=[...Ah];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Du.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Du.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(Nu(i)){let T=O.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),m.prefs["download.default_directory"]="C:\\Users\\testnode",r.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),r.desiredCapabilities["aws:maxDurationSecs"]=2400,r.desiredCapabilities["aws:idleTimeoutSecs"]=60}Nu(i)&&c==="MicrosoftEdge"&&(r.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`));try{let T=Go();T.length&&T.forEach(v=>d.push(`--disable-features=${v}`))}catch{}e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Du.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(b=(g=e.projectData)==null?void 0:g.defaults)!=null&&b.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(r.desiredCapabilities,{browserName:c});function p(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+ul.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}p(),Oh(s,l,o),a===J.EXTENSION&&_h(e,l,d,n,o),l.length>0&&(m.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[c],h={MicrosoftEdge:"ms",chrome:"goog"}[c];return Kt.isLambdatestGrid(i)&&delete m.w3c,e.oldCapabilities&&i.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(r.desiredCapabilities[f]=m),(e.w3cCapabilities||i.type==="testimEnterprise")&&(r.desiredCapabilities[`${h}:${f}`]=m),r}function bE(r,e,t){let s={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(s,{"browser.helperApps.neverAsk.saveToDisk":Eh.join(","),"browser.helperApps.neverAsk.openFile":Eh.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(r.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:s}},t!=null&&t.isLambdatestRun()?{"LT:Options":{enableCustomTranslation:!0}}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(r.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(r.desiredCapabilities["moz:firefoxOptions"].args||(r.desiredCapabilities["moz:firefoxOptions"].args=[]),r.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),r}function vs(r){return`${r.width}x${r.height}`}function IE(r){let{platform:e}=r;if(!e)return vs(Ih);let t=e.split(" ")[1];return e.startsWith("Windows")&&EE.has(t)?vs(wE):e==="Linux"?vs(TE):e.startsWith("macOS")?vs(vE):vs(e==="OS X El Capitan"||e==="OS X Yosemite"?SE:Ih)}function RE(r,e,t){let{saucelabs:s}=r;if(s!=null&&s.browserVersion&&(s.version=s.browserVersion),s!=null&&s.username&&s.accessKey){let i={"sauce:options":{name:e}};if(i["sauce:options"].screenResolution=IE(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version;let n=s.appiumVersion||t.sl.appiumVersion;n&&(i["sauce:options"].appiumVersion=n);let o=["screenResolution","appiumVersion"];t.browserValue!=="safari"&&o.push("safari_version");let a=Ve.omit((0,Ch.cloneDeep)(t.sl),o);return Ve.merge(a,i,s)}return Ve.merge(i,s)}return{}}function xE(r){let{runnerOptions:e}=r;if(Ve.isEmpty(e.browserstack))return{"bstack:options":{}};let{projectData:t,testRunConfig:s,testId:i,testName:n,executionId:o,executionName:a}=r,c={"bstack:options":{buildName:`${a} - ${o}`,sessionName:`${n} - ${i}`,projectName:`${t.name} - ${t.projectId}`,...e.browserstack}};return s&&s.browserValue==="safari"&&s.bs.safari_version&&(c["bstack:options"].os_version=s.bs.safari_version,s.bs.safari_version==="10"&&Object.assign(c["bstack:options"],{"safari.options":{technologyPreview:!0}})),c}function CE(r){return r.perfecto?r.perfecto:{}}function AE(r,e,t){if(r.experitestToken){let s=e==="safari";return{accessKey:r.experitestToken,browserVersion:"latest",platformName:s?"MAC":"WIN10",seleniumScreenshot:s,newSessionWaitTimeout:t}}return{}}function PE(r,e={}){let{gridData:t={},gridUsername:s,gridPassword:i}=r,n=s||t.user||e.user,o=i||t.key||e.key,a={};return n&&o&&(a.Authorization=xc(n,o)),a}function Go(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(r=>r.trim().length)}function Ho(r){var B,V,I,k;let{overrideConfiguration:e,browserOptions:t,testId:s,testName:i,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:d,testResultId:m,lambdatestService:p,mode:f,customCapabilities:h,useLocalChromeDriver:g}=r;if(o.mode==="local"){let L=[],j=[...Ah],G={};t.headless&&j.push("--headless"),t.silentDebuggerExtensionApi&&j.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&j.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let se=Go();se.length&&se.forEach(he=>j.push(`--disable-features=${he}`))}catch{}t.chromeExtraArgs&&t.chromeExtraArgs.forEach(se=>j.push(`--${se}`)),t.chromeBinaryLocation&&(G.binary=t.chromeBinaryLocation);let K,q=null;return f!==J.SELENIUM&&(K=_h(t,L,j,null,p,g)),q=Oh(a,L,p,g),g&&j.push("--enable-unsafe-extension-debugging","--remote-debugging-pipe"),{logLevel:wh,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:j,extensions:L,...G},browserName:"chrome",...g&&{webSocketUrl:!0}},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515,...g&&K&&{unzippedTestimExtensionPath:K},...g&&q&&{unzippedCustomExtensionPath:q}}}let{driverRequestTimeout:b,driverRequestRetries:T}=t,v=PE(t,o),y={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:wh,connectionRetryTimeout:b,connectionRetryCount:T,getSessionTimeout:Math.max(p.getSessionTimeout,t.getSessionTimeout),getSessionRetries:p.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0},...!Ve.isEmpty(v)&&{headers:v},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};if(Nu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,y.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(y.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key),o.type==="local"){let L=new URL(o.host.startsWith("http")||o.host.startsWith("https")?o.host:`${o.protocol}://${o.host}`);y.user=L.username,y.key=L.password,y.hostname=L.hostname,y.host=L.hostname}let w=Number(t.browserTimeout/1e3),S=t.browser||(n==null?void 0:n.browserValue),C={runnerOptions:t,testId:s,testName:i,testRunConfig:n,executionId:c,executionName:l,projectData:d};Ve.merge(y.desiredCapabilities,RE(t,i,n),xE(C),CE(t),AE(t,S,w),p==null?void 0:p.getCapabilities(t,S,c,m,i,n,e,f));let _=null;switch(!t.ext&&!t.extensionPath&&((B=o.host)!=null&&B.endsWith(".testim.io"))&&!t.canary&&f===J.EXTENSION&&(S==="chrome"||S==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(_="/opt/testim-headless"),S){case"chrome":case"edge-chromium":y=yE(y,t,n,a,o,_,p,f);break;case"firefox":y=bE(y,t,p);break;case"safari":case"safari technology preview":y=gE(y,S);break;default:break}h?(Vo(h,o.type),Ve.merge(y.desiredCapabilities,h)):Ve.merge(y.desiredCapabilities,t.seleniumCapsFileContent);try{let L={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},j=se=>se[o.provider]||se[y.host]||se[L[y.host]],G=se=>{var he,ze;return j(se)||se[(he=y.desiredCapabilities)==null?void 0:he.browserName]||se[(ze=y.desiredCapabilities)==null?void 0:ze.version]||se||{}},K=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),q=G(G(K));Object.keys(q).length&&(Ss.info(`Adding custom capabilities: ${JSON.stringify(q)}`),Object.assign(y.desiredCapabilities,q))}catch(L){Ss.error("Failed to load custom capabilities",{error:L,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(y.desiredCapabilities&&!y.capabilities&&(fE(y),y.capabilities={alwaysMatch:y.desiredCapabilities,firstMatch:[{}]},delete y.desiredCapabilities),y.capabilities||={alwaysMatch:{},firstMatch:[{}]},y.capabilities.alwaysMatch||={},y.capabilities.alwaysMatch["wdio:enforceWebDriverClassic"]=!0,y.hostname=y.host,r.printFinalCaps){let L=(V=y.capabilities)==null?void 0:V.alwaysMatch,j=JSON.parse(JSON.stringify(y)),G=(I=j==null?void 0:j.capabilities)==null?void 0:I.alwaysMatch,K=se=>se.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(se=>{var he,ze;G!=null&&G[se]&&(G[se].extensions=(ze=(he=L==null?void 0:L[se])==null?void 0:he.extensions)==null?void 0:ze.map(K))}),G!=null&&G.loadExtension&&(G.loadExtension=(k=L==null?void 0:L.loadExtension)==null?void 0:k.map(K));let q=require("node:util");console.log(q.inspect(j,{showHidden:!1,depth:null,colors:!0}))}return y}var Rh,_r,xh,Ve,Ch,Ss,wh,Du,Ah,Ph,vh,Sh,Mu,Nu,fE,yE,Eh,Ih,TE,wE,vE,SE,EE,zo=E(()=>{"use strict";Rh=R(require("node:fs")),_r=R(require("node:path")),xh=R(require("node:crypto")),Ve=R(require("lodash"));U();ue();W();cl();U();pe();oe();Wo();Lu();Ch=require("lodash"),Ss=A("testim-desired-capabilities-builder"),wh=_n?"debug":"silent",Du={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Ah=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],Ph=_r.join(Tt,"extensions"),vh=_r.join(Ph,"testim-headless"),Sh=_r.join(Ph,"custom-extension"),Mu=(...r)=>xh.createHash("sha256").update(r.join("")).digest("hex"),Nu=r=>r.type===N.DEVICE_FARM||r.type===N.HYBRID&&r.provider==="devicefarm",fE=r=>{var s;let{desiredCapabilities:e}=r;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),((s=e["goog:chromeOptions"])==null?void 0:s.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in r.desiredCapabilities&&(r.user=r.desiredCapabilities.username,delete r.desiredCapabilities.username),"accessKey"in r.desiredCapabilities&&(r.key=r.desiredCapabilities.accessKey,delete r.desiredCapabilities.accessKey);let t;try{t=O.flags.unsupportedCapsFields.getValue();let i=JSON.parse(t);if(!Array.isArray(i))return;i.forEach(n=>{delete e[n]})}catch{Ss.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};yE=Ve.memoize(hE,(r,e,t,s,i,n)=>{let o=JSON.stringify(r.desiredCapabilities),a=JSON.stringify(Ve.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(i.type);return Mu(o,a,c,s,l,n)}),Eh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Ih={width:1920,height:1080},TE={width:1920,height:1200},wE={width:2560,height:1600},vE={width:2360,height:1770},SE={width:2048,height:1536},EE=new Set(["7","8","8.1","10","11"])});function Ft(r){var e,t,s,i,n,o,a,c;return((e=r.message)==null?void 0:e.match(/Command not found/))||r.message==="HTTP method not allowed"||((t=r.message)==null?void 0:t.toLowerCase())==="unknown error"||((s=r.message)==null?void 0:s.match(/Unknown timeout type/))||r.name==="unknown command"||((i=r.message)==null?void 0:i.match(/did not match a known command/))||((n=r.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=r.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=r.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((c=r.message)==null?void 0:c.match(/\.\w* is not a function/))}function Dh(r,e,t){if(!e||!r)return r;if(r.includes("%"))return r.replace(/ /g,"%20");try{return decodeURI(r)!==r?r:encodeURI(r)}catch(s){return t&&t.warn("tried to encode url but failed",{err:s,url:r}),r}}var Fu=E(()=>{"use strict"});function Uu(r){function e(p){return p?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(p.nodeType):!1}function t(p){return p?s(p.parentNode,e):null}function s(p,f){for(let h=p;h&&h!==p.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function i(p,f){for(let h=p;h&&h!==p.ownerDocument;h=t(h))if(f(h))return h;return null}function n(p,f){if(!p||!f)return null;p instanceof DocumentFragment&&(p=p.host);let g=window.getComputedStyle(p).getPropertyValue(f);if(g&&g!=="inherit")return g;let b=t(p);return n(b,f)}function o(p){let f=p.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(p.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=n(p,"stroke-width");return!!g&&parseInt(g,10)>0}return n(p,"overflow")==="hidden"?!1:Array.from(p.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(p){return n(p,"overflow")==="hidden"}function c(p){return!p||!a(p)||!p.childNodes.length?!1:Array.from(p.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:c(f))}function l(p){var f;return p?(f=p.parentNode)!=null&&f.host?!0:l(p.parentNode):!1}if(!r||!l(r)&&!document.contains(r))return!1;switch(r.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=s(r,h=>h.tagName.toUpperCase()==="SELECT");return Uu(f)}case"INPUT":if(r.type==="hidden")return!1;break;default:break}if(n(r,"visibility")!=="visible")return!1;let d=!!i(r,p=>Number(n(p,"opacity"))===0),m=!!i(r,p=>n(p,"display")==="none");return!(d||m||!o(r)||c(r))}var Nh=E(()=>{"use strict"});var Mh,Fh,Ut,kE,OE,qo,Uh=E(()=>{"use strict";Mh=R(require("promise-queue")),Fh=R(require("webdriverio"));ue();je();U();W();Gr();Nh();Fu();Ts();Ut=A("WebDriverApi"),kE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},OE={implicit:0,pageLoad:1,script:2},qo=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}rejectWithLog(e,t){let{testName:s,testResultId:i}=this,n=t?t.toString().slice(0,2e3):"";throw Ut.warn("error from selenium",{err:e,testResultId:i,testName:s,crashingFunc:n}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),kc!==void 0&&(e=kc);let t=1/0;this.queue=new Mh.default(e,t)}async addToQueue(e){var s,i;let t=(s=this.seleniumPerfStats)==null?void 0:s.markStart();try{return await this.queue.add(e)}catch(n){return this.rejectWithLog(n,e)}finally{(i=this.seleniumPerfStats)==null||i.markEnd(t)}}async installExtensions(e){var s;let t=[e==null?void 0:e.unzippedTestimExtensionPath,e==null?void 0:e.unzippedCustomExtensionPath].filter(Boolean);for(let i of t)await((s=this.client)==null?void 0:s.send({method:"webExtension.install",params:{extensionData:{type:"path",path:i}}}))}async initClient(e,t,s,i,n){var c,l,d,m,p,f,h,g;this.testName=t,this.testResultId=s,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let o=((c=e.capabilities.alwaysMatch)==null?void 0:c.loadExtension)||((l=e.capabilities.alwaysMatch)==null?void 0:l.loadExt)||((f=(p=(m=(d=e.capabilities.alwaysMatch)==null?void 0:d["goog:chromeOptions"])==null?void 0:m.extensions)==null?void 0:p[0])==null?void 0:f.slice(0,80)),a=(h=this.seleniumPerfStats)==null?void 0:h.markStart(ke.GET_BROWSER);try{await this.addToQueue(async()=>{Ut.info("requesting browser",{testResultId:s,testName:t,extUrl:o}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=s??"",this.client=await Fh.remote(e),this.client.on("dialog",async b=>{try{await b.accept()}catch{}}),i&&await this.installExtensions(n),this.logGridStatus(s)}),M("after client init")}finally{(g=this.seleniumPerfStats)==null||g.markEnd(a,ke.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,s="N/A",i="N/A",n;try{n=await this.client.status();for(let a of n.nodes||[])for(let c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){s=a,i=c;break}}catch(a){if(a.message==="unknown error"){Ut.info("grid status is not supported by the grid",{testResultId:e});return}Ut.error("failed to get grid status",{error:a,testResultId:e});return}s&&typeof s=="object"&&"slots"in s&&(s==null||delete s.slots),Ut.info("grid status",{gridStatusMsg:n.message,ready:n.ready,browserNode:s,gridSlot:i,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let i=a=>{throw Object.assign(a,{executedScript:e}),a},n=()=>this.client.execute(e,t).catch(i),o=()=>this.client.executeScript(e,t).catch(i);if(this.unsupportedActions.has("execute"))return n();t=t.map(a=>{if(a===null){Ut.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(Ft(a))return this.unsupportedActions.add("execute"),n();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let i=()=>this.client.execute(e,...t),n=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return i();try{return await n()}catch(o){if(Ft(o))return this.unsupportedActions.add("executeAsync"),i();throw o}})}}async executeCDP(e,t={}){var i;if(!this.isChromium())return;let s=await((i=this.client)==null?void 0:i.sendCommandAndGetResult(e,t));return s!=null&&s.targetInfos?s.targetInfos:[]}async takeScreenshot(){var t,s;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(ke.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.takeScreenshot()})}}finally{(s=this.seleniumPerfStats)==null||s.markEnd(e,ke.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(ke.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Fe(e)))}finally{this.seleniumPerfStats.markEnd(t,ke.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(async()=>{var s;return(s=this.client)==null?void 0:s.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(i=>({value:i})),s=()=>this.execute(Uu,{ELEMENT:e,[Qt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return s();try{return await t()}catch(i){if(Ft(i))return this.unsupportedActions.add("elementIdDisplayed"),s();throw i}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Dh(e,this.isSafari(),Ut))})}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 s=()=>{let n=[];return n[OE[e]]=t,this.client.setTimeouts(...n)},i=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return i();try{return await s()}catch(n){if(Ft(n))return this.unsupportedActions.add("timeouts"),i();throw n}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let s=function(i,n){window.scrollTo(i,n)};return this.execute(s,e,t)}async setValue(e,t){return await this.elementIdClear(Fe(e)),await this.elementIdValue(Fe(e),t)}async getViewportSize(e){let t=await this.execute(kE);if(typeof e=="string"&&/(width|height)/.test(e)){let s=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[s]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let s=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.elementSendKeys(e,s)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitFormManually(e){return this.addToQueue(async()=>{var n;let t=(n=this.client)==null?void 0:n.$(e),s=t.$('button[type="submit"]');return await s.isExisting()?s.click():t.$("input:last-of-type").keys("Enter")})}async findElementAndPress(e,t,s){let i;try{i=await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:s})})}catch(n){if(n.message.includes("unexpected alert open")||n.message.includes("dialog detected"))await this.alertAccept().catch(o=>Ut.warn("failed to click on alert",{err:o})),i=await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:s})});else throw n}return{value:i}}_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 s;return(s=this.client)==null?void 0:s.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).dragAndDrop(t)})}}moveTo(e,t,s){let i={...typeof t=="number"&&{xOffset:t},...typeof s=="number"&&{yOffset:s}};return this.isSafari()&&!Object.hasOwn(i,"yoffset")&&(i.yOffset=1),this.isSafari()&&!Object.hasOwn(i,"xoffset")&&(i.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let n=this.client.$(e);await this.client.action("pointer").move({origin:n}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.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 s=async()=>await this.client.getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),n=Math.abs(e.height);s=async()=>await this.client.setWindowSize(i,n)}try{return await s()}catch(i){throw i}})}}setCookie(e,t,s,i,n,o,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:s,httpOnly:i,secure:n,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var s;return(await((s=this.client)==null?void 0:s.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayed()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchFrame(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,s;await((s=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:s.call(t)),e(!0)})}catch(e){Ut.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.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 s;return(s=this.client)==null?void 0:s.isAppInstalled(e)});return Ut.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 lr={};z(lr,{getSessionPlayer:()=>ee,options:()=>ju});var Ko,ju,Bu,ee,ve=E(()=>{"use strict";Ko=require("path");W();ju={playerPath:void 0},ee=()=>{if(Bu)return Bu;let r=(je(),Ue(Be));r.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(gi(),Ue(fi)),t=e(),s=ju.playerPath?(0,Ko.resolve)(ju.playerPath,"src/background/sessionPlayerInit.ts"):(0,Ko.join)(t,"sessionPlayer.js"),i=require(s);return r.log("getSessionPlayerRequire end"),Bu=i,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&i.setLoggerFormatter&&i.setLoggerFormatter(Lm),i}});var Bh={};z(Bh,{doubleClick:()=>_E});var _E,jh=E(()=>{"use strict";_E=function(r,e){let t=["pointerup","pointerdown","pointermove"],s=getLocatedElement(r.locatedElement);if(!s)throw new Error("element not found");let i=r.events,n={status:"done",success:!0};window.__unloadNavigator=function(){e(n)};let o=function(p){function f(v,y,w){return w>v&&w<y}let h=p.pointerPosition||{},g=s.getBoundingClientRect(),b=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:b,y:T}},a=function(p,f){return{screenX:0,screenY:0,clientX:p,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(p,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(p,g)},l=function(p,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(p,!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 p=document.activeElement;for(;(f=p.shadowRoot)!=null&&f.activeElement;)p=p.shadowRoot.activeElement;return p},m=function(p){let f=o(p),h=p.event;return t.includes(h)?c(h,f.x,f.y):l(h,f.x,f.y)};try{i.map(f=>m(f)).filter(Boolean).forEach(f=>s.dispatchEvent(f));let p=d();dispatchFocus(r.elementToFocusLocatedElement,p),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(n)}catch(p){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:p.toString(),success:!1})}}});var Hi={};z(Hi,{dispatchFocus:()=>LE});function LE(r,e){function t(n){let o=document.createEvent("HTMLEvents");return o.initEvent(n,!0,!1),o}function s(){var o;let n=document.activeElement;for(;(o=n.shadowRoot)!=null&&o.activeElement;)n=n.shadowRoot.activeElement;return n}function i(n,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),n.dispatchEvent(t("focusin")),n.dispatchEvent(t("focus")),typeof n.focus=="function"&&n.focus();let a=s();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(r){let n=getLocatedElement(r);if(n&&n!==e)try{i(n,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var zi=E(()=>{"use strict"});var Hh={};z(Hh,{WebDriver:()=>Dr});async function FE(r){var e,t;try{let s=(t=(e=r==null?void 0:r.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return s?await NE(s):void 0}catch(s){Ge.info("Error getting cdpAddress",s);return}}var Is,Vh,Gh,Ge,Es,DE,$h,NE,Lr,ME,Wh,qi,Dr,Ki=E(()=>{"use strict";Is=R(require("lodash"));U();je();zo();Vh=R(require("p-retry")),Gh=R(require("ua-parser-js"));Gr();W();Fu();Uh();Q();pe();Ts();Ge=A("webdriver"),[Es,DE]=[0,2],{extractElementId:$h,getCdpAddressForHost:NE}=Y,Lr=()=>(ve(),Ue(lr)).getSessionPlayer().codeSnippets,ME=()=>(ve(),Ue(lr)).getSessionPlayer().locatorBuilderUtils,Wh=()=>(ve(),Ue(lr)).getSessionPlayer().utils,qi=()=>(ve(),Ue(lr)).getSessionPlayer().positionUtils;Dr=class extends qo{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.keepAliveFailedCallbacks=[];this.generalKeepAliveFailures=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null)}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(s=>s!==t)}registerToKeepAliveFailed(t){this.keepAliveFailedCallbacks.push(t)}unregisterToKeepAliveFailed(t){this.keepAliveFailedCallbacks=this.keepAliveFailedCallbacks.filter(s=>s!==t)}async init(t){var B,V,I,k,L,j,G,K;let{projectData:s,overrideConfiguration:i,browserOptions:n,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:p,testResultId:f,seleniumPerfStats:h,fastInit:g,lambdatestService:b,printFinalCaps:T,mode:v,customCapabilities:y,useLocalChromeDriver:w}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=!!((I=(V=(B=n==null?void 0:n.company)==null?void 0:B.activePlan)==null?void 0:V.premiumFeatures)!=null&&I.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let S=Ho({projectData:s,browserOptions:n,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:p,testResultId:f,lambdatestService:b,overrideConfiguration:i,printFinalCaps:T,mode:v,customCapabilities:y,useLocalChromeDriver:w});S.desiredCapabilities&&delete S.desiredCapabilities.marionette,S.capabilities&&delete S.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(b==null?void 0:b.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=h;let C=g?0:1500,_=g?(()=>null):()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let q={unzippedTestimExtensionPath:S.unzippedTestimExtensionPath,unzippedCustomExtensionPath:S.unzippedCustomExtensionPath},se=await this.initClient(S,a,f,w,q);M("after initResult before getCdpAddress in init"),this.cdpUrl=await FE(se),M("after getCdpAddress in webdriver.js init"),Ge.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await ie(C),O.flags.dontFocusOnInit.isEnabled()||await _(),M("after focus and delay in webdriver.js init")}catch(q){let se=JSON.stringify(Is.omit(S,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Ge.error("failed to init webdriver",{err:q,capabilitiesAsString:se});let he=((L=(k=n==null?void 0:n.company)==null?void 0:k.activePlan)==null?void 0:L.plan)==="free";throw(j=q.stack)!=null&&j.includes("at startWebDriverSession")&&((G=q.message)!=null&&G.startsWith("Failed to create session"))&&((K=q.message)!=null&&K.includes("Timeout awaiting 'request'"))&&he?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(q.message)?new qr(q.message):/capabilit(y|ies)/.test(q.message)&&!/UND_ERR_HEADERS_TIMEOUT/.test(q.message)?new Fn(q.message):/403 Forbidden/.test(q.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(q.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${q.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=n=>Is.zip(n.slice(0,-1),n.slice(1)),s=this._keepAliveRequests.map(({start:n})=>n).filter(Boolean),i=t(s).map(([n,o])=>o-n);return Math.max(...i)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(i=>t.message.includes(i))}start(){if(this.started)return;this.started=!0;let t=async()=>{let s=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),i=(a,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function n(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=ce();s(o);try{await this.executeJS(n),this._isAlive=!0,i("end",o),this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0}catch(a){if(i("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,Ge.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Ge.warn("failed to click on alert",{err:c}));return}if(Ge.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Ge.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.handleThresholdBasedError(this.browserClosedCallbacks,a)}else this.generalKeepAliveFailures++,this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures>=3&&this.handleThresholdBasedError(this.keepAliveFailedCallbacks,a)}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}handleThresholdBasedError(t,s){t.forEach(i=>{try{i(s)}catch{}})}async switchToLocatedFrame(t){let s=await this.getElement(t);if(!s.value)throw new Error("Element not found");let i=$h(s.value);return await this.switchFrame({ELEMENT:i,[Qt]:i}),s}switchFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(s){throw(t=s.message)!=null&&t.includes("ECONNREFUSED")?new Un:s}}async getElement(t){var n;let s=this.seleniumPerfStats.markStart(ke.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(s,ke.GET_ELEMENT)}if(((n=t==null?void 0:t.shadowPath)==null?void 0:n.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
18
|
+
\r`)))}onTestPlanFinished(e,t,s,i,n){let o=Eo(e),a=Io(e),c=Ro(e),l=a.length,d=c.length,m=o.length,p="",f="";if(Nt.isTestStatusEnabled){let v=So(e);p=` FAILED-EVALUATING: ${v}`,m-=v,f=` SKIPPED: ${vo(e,this.options)}`}let h=this.buildTestPlanName(n,t),g,b=Pr[m?"error":"success"],T=`PASSED: ${l} FAILED: ${m}${p} ABORTED: ${d}${f} Duration: ${Hn(s)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${i})`:g=`Test plan${h} completed ${T} (${i})`,this.printWorkerDivider(),console.log(b(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let s=Oi.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,i=Oi.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,n=Oi.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Oi.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[n,i,s,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,s,i,n,o,a){let c=p=>{p.forEach((f,h)=>{var v;let g=(v=f.testData)!=null&&v.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",b=`(${f.testId})`,T="";f.testOptimization?T=` [${f.testOptimization.reason}]`:Ze(f,this.options)&&(T="-quarantine"),console.log(" ",h+1,":",`${f.name}${T}`,b,g)})},l=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,i)} test plan with ${m} (${n})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),s.length>0&&(console.log("After all:"),c(s)),this.printWorkerDivider()}onGetSlot(e,t){let s=this.options.grid||this.options.gridId,i=this.options.mode===Po.APPIUM?xg:t;s&&console.log(this.toWorkerIdPrefix(e),`Get ${or.default.underline(i)} slot from ${or.default.underline(s)}`)}onGetSession(e,t,s){let i=s===Po.APPIUM?xg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${i} to run ${or.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,s){if(s!==2)return;let i=this.options.grid||this.options.gridId,n=this.options.mode===Po.APPIUM?"device":"browser";if(i)console.log(Pr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${n} from the grid ${i}`));else if(this.options.useLocalChromeDriver)console.log(Pr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===Po.APPIUM?"Appium":"Selenium";console.log(Pr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},xS=ru});var au={};z(au,{Reporter:()=>_S});function CS(r){let e=r.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${r.name}${t}`}function AS(r){return r.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${r.visitedUrlsList||""}`}function PS(r){return`${r.visitedUrlsJson||""}`}async function kS(r,e,t,s,i,n){function o(p){let f=qe(r,t,p.testId,p.resultId,s),h={$:{name:CS(p),classname:i,time:yl(p.duration),ownedBy:p.testOwnerName,ownerEmail:p.testOwnerEmail},"system-out":f};if(Pi(p)||Ql(p)){let g=`Step Failed: ${p.failureReason||p.reason}`,b=Pi(p)?`${g} More info at: ${f}`:g;h.failure={$:{message:b}}}return Zl(p)&&Ze(p,n)&&Nt.isTestStatusEnabled&&(h.skipped={}),n.urls&&(h["visited-urls-list"]=AS(p),h["visited-urls-json"]=PS(p)),h}function a(p){let{results:f,testPlanName:h,configName:g}=p,b=f||{},v={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(b),failures:d(b),timestamp:c(e)};if(Nt.isTestStatusEnabled){v.skipped=vo(b,n);let y=So(b);v.failures-=y,v["failure-evaluating"]=y}return{$:v,testcase:Object.keys(b).map(y=>o(b[y]))}}function c(p){let f=Object.keys(p).map(g=>p[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function l(p){return Object.keys(p).length}function d(p){return Eo(p).length+Ro(p).length}let m={testsuites:{testsuite:e.map(p=>a(p))}};try{return new ou.Builder().buildObject(m)}catch(p){return OS(p)}}function OS(r){let e=new ou.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:r.message}}}}}};return e.buildObject(t)}var ou,Cg,nu,_S,cu=E(()=>{"use strict";ou=R(require("xml2js"));U();Cg=require("fs");ki();xo();nu=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,s=this.options.project,i=await kS(this.options.editorUrl,e,s,this.branchToUse,this.classname,this.options);if(t)try{return await Cg.promises.writeFile(t,i),console.log("JUnit XML file saved to",t),e}catch(n){return console.error("could not save report file",t,n),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};_S=nu});var Ag={};z(Ag,{Reporter:()=>LS});function fs(r){return r?r.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 lu,uu,LS,Pg=E(()=>{"use strict";W();lu=A("team-city-reporter");uu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},s=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",i=`${e.name} (${e.testId})${s}`;return fs(i)}onTestStarted(e,t,s,i){if(s){lu.debug("skip report test started because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testStarted name='${n}' captureStandardOutput='true' flowId='${i}']`)}onTestFailed(e,t,s,i,n,o){if(n){lu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${fs(t)}' details='${fs(s)}' flowId='${o}']`)}onTestFinished(e,t,s){if(s){lu.debug("skip report test finished because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testFinished name='${i}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,s="ignore"){let i=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${i}' message='${fs(s)}']`)}onTestPlanStarted(e,t,s,i){console.log(`##teamcity[testSuiteStarted name='${fs(i)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${fs(t)}']`)}},LS=uu});var kg={};z(kg,{Reporter:()=>DS});var pu,DS,Og=E(()=>{"use strict";pu=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,s,i,n){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:n}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},DS=pu});function Oo(r){let{platform:e}=process;e==="win32"?(0,ko.exec)(`start chrome ${r}`):e==="darwin"?(0,ko.exec)(`open -a "Google Chrome" ${r}`):e==="linux"&&(0,ko.exec)(`google-chrome ${r}`)}var ko,du=E(()=>{"use strict";ko=require("child_process")});var _g={};z(_g,{Reporter:()=>NS});var mu,NS,Lg=E(()=>{"use strict";U();du();mu=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 Oo(t)}},NS=mu});var fu,te,Mt=E(()=>{"use strict";Rg();fu=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 s=e.reporters;if(this.reporters.push(new Ao(e)),s===void 0||s.length===0){let{Reporter:i}=await Promise.resolve().then(()=>(iu(),su));if(this.reporters.push(new i(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:n}=await Promise.resolve().then(()=>(cu(),au));this.reporters.push(new n(e,t))}}else(await Promise.all([s.includes("teamcity")&&Promise.resolve().then(()=>(Pg(),Ag)),s.includes("console")&&Promise.resolve().then(()=>(iu(),su)),s.includes("junit")&&Promise.resolve().then(()=>(cu(),au)),s.includes("json")&&Promise.resolve().then(()=>(Og(),kg)),s.includes("chrome")&&Promise.resolve().then(()=>(Lg(),_g))])).forEach(n=>{n&&this.reporters.push(new n.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,s,i,n){let o={};o=e;let a=Date.now()-(s||0);return[o,t,a,i,n]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...s)=>{var n;let i=t==null?void 0:t(...s);for(let o of this.reporters)await((n=o[e])==null?void 0:n.call(o,...i||s))}}},te=new fu});async function gu(r,e,t){let s=gs[r];if(!s)return;let{slotId:i}=s;if(delete gs[r],!i){St.warn("failed to find slot slot id",{companyId:e,workerId:r});return}St.info("release slot id",{companyId:e,slotId:i});try{await yu(e,t,i)}catch(n){St.error("failed to release slot",{companyId:e,err:n})}}async function MS(r,e){let t=Object.values(gs).filter(Boolean);if(t.length!==0)try{await Tu(r,e,t)}catch(s){St.error("failed to update slot keep alive",{err:s,slots:t,companyId:r})}}function FS(r,e){Dg=global.setInterval(()=>MS(r,e),1e4)}async function US(r,e){let t=Object.keys(gs);if(t.length){St.warn("not all slots released before end runner flow",{companyId:r});try{await ne(t,s=>gu(Number(s),r,e))}catch(s){St.error("failed to release all slots",{err:s,companyId:r})}}}async function BS(r,e){await US(r,e),clearInterval(Dg)}async function Mg(r,e,t){let s;try{s=await hu(r,e)}catch(i){throw St.error("failed to get slot",{companyId:r,err:i}),new Error(bt.UNKNOWN)}if(St.info("get slot info",{...s,companyId:r}),!s||!["success","error"].includes(s.status))throw St.error("invalid response - get slot",{res:s}),new Error(bt.UNKNOWN);if(s.status==="success")return Ng(t,{slotId:s.slotId}),s.slotId;throw s.code==="not-found"?new nt(bt.NOT_FOUND):s.code==="no-available-slot"?new tr("Failed to run test - concurrency limit reached"):(St.error("invalid code error response - get slot",{res:s}),new nt(bt.UNKNOWN))}async function Fg(r,e,t,s){let i=gs[s];if(!i)throw new Error("slot not found");Object.assign(i,t),Ng(s,i),await bu(r,e,i),St.info("update slot data on server",{companyId:r,projectId:e,slotData:t})}var St,gs,Dg,Ng,_i,hs=E(()=>{"use strict";fe();W();U();oe();Q();St=A("slot-service"),gs={},Dg=null,Ng=(r,e)=>{gs[r]=e};_i={start:FS,end:BS}});function Bg(r,e=process){async function t(s){await ae(ne(Ug,async i=>i()),1e4).catch(()=>null),r(s)}e.on("uncaughtException",async s=>{s.message.includes("Command browsingContext")||(Di.error("Caught exception",{err:s}),console.log("Uncaught exception"),s.message&&console.log("Message =",s.message),s.reason&&console.log("Reason =",s.reason),await t(s))}),e.on("unhandledRejection",s=>{var i;if(Di.fatal("Caught unhandled promise rejection",s),!((i=s==null?void 0:s.message)!=null&&i.includes("ENOTFOUND x-api.rollout.io")))throw s}),e.on("rejectionHandled",()=>{Di.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let s="Runner aborted - SIGTERM event",i=new Error(s);throw Di.error(s),t(i),i}),e.once("SIGINT",()=>{let s="Runner aborted - SIGINT event",i=new Error(s);throw Di.error(s),t(i),i}),e.once("exit",s=>{r(s)})}function ys(r){Ug.push(r)}var Di,Ug,Ni=E(()=>{"use strict";W();U();Di=A("process-handler"),Ug=[]});var Vg={};z(Vg,{installAllLazyDependencies:()=>VS,lazyRequire:()=>dt});async function dt(r,e={}){let t=Cl(r);if(t)return t;let s;e.silent||(s=(0,jg.default)(`Installing ${r} before first usage...`).start());try{let i=await WS(r);return s&&s.succeed(),i}catch(i){$S.warn("failed to install dependency lazily",{dependency:r,err:i});let n=Wg(r),o=`${r}@${n}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${r} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${o}`;throw s&&s.fail(l),i}}async function WS(r){return bs.has(r)||(bs.set(r,$g(r)),bs.get(r).catch(()=>{bs.delete(r)})),bs.get(r)}async function $g(r){let e=Cl(r);if(e)return e;let t=Wg(r),s=`${r}@${t}`;return await no(yt(),s),nr(r)}async function VS(){let r=Object.keys(Pc);for(let e of r)await $g(e)}function Wg(r){let e=Object.entries(Pc).find(([t])=>t===r);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var jg,$S,bs,Mi=E(()=>{"use strict";jg=R(require("ora"));ls();W();U();kn();pi();$S=A("lazy-require"),bs=new Map});var Gg,_o,Hg=E(()=>{"use strict";Gg=require("istanbul-lib-report"),_o=class extends Gg.ReportBase{constructor(e){super(),e||={},this.appendToObject=e.appendToObject||{}}onStart(e){let t=e.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,t.toJSON())}}});var zg,qg,Kg,Fi,Et,Jg,Lo,wu,Xg,GS,Yg,Qg,HS,zS,Zg,qS,KS,JS,XS,YS,eh,th=E(()=>{"use strict";zg=R(require("ora")),qg=R(require("dayjs")),Kg=R(require("test-exclude")),Fi=R(require("fs")),Et=R(require("path")),Jg=R(require("istanbul-reports")),Lo=R(require("istanbul-lib-report"));fe();Q();U();W();Mi();Hg();wu=A("test-run-status"),Xg=r=>{try{return new URL(r)}catch{try{return new URL(`file://${r}`)}catch{return{}}}},GS=r=>!!Xg(r).search,Yg=r=>r?Xg(r).pathname.substring(1):"",Qg=(r,e)=>{let t=Yg(e);return!new Kg.default({relativePath:!1,include:r}).shouldInstrument(t)},HS=r=>r.substring(0,r.indexOf("?")),zS=async({source:r,sourceMapDir:e,sourceMapType:t})=>{let s=await dt("convert-source-map");if(t==="file"&&!e)throw new x("--code-coverage-source-map-path [path]");return e?s.fromMapFileSource(r,e):s.fromSource(r)},Zg=(r,e)=>`${Et.resolve(r,Yg(e))}.js`,qS=async(r,e,t)=>{let{codeCoverageInclude:s}=r;await ne(Object.values(t),async i=>{if(!i)return;let n=i.toObject();await ne(n.sources,async(o,a)=>{if(Qg(s,o))return;let c=Zg(e,o);await Fi.promises.mkdir(Et.parse(c).dir,{recursive:!0}),await Fi.promises.writeFile(c,n.sourcesContent[a])})})},KS={getPath(r){if(typeof r=="string")return r;let e=r.getQualifiedName();return r.isSummary()?e!==""?e+="/index.html":e="index.html":(GS(e)&&(e=HS(e)),e+=".html"),e},relativePath(r,e){let t=this.getPath(e),s=Et.dirname(this.getPath(r));return Et.posix.relative(s,t)},assetPath(r,e){return this.relativePath(this.getPath(r),e)}},JS=async(r,e,t,s)=>{let{codeCoverageReporter:i}=r,n={},o=Lo.createContext({dir:t,coverageMap:e,watermarks:Lo.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Zg(s,a);return Fi.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new _o({appendToObject:n}).execute(o),Array.isArray(i)&&i.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:KS}),Jg.create(a,c).execute(o)}),n},XS=async(r,{source:e,sourceMap:t,functions:s})=>{let{codeCoverageInclude:i}=r;if(!t||t.sourcemap.sources.length===0)return;let o=(await dt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Qg(i,a));return await o.load(),o.applyCoverage(s),o.toIstanbul()},YS=async(r,e)=>{let{mergeProcessCovs:s}=await dt("@bcoe/v8-coverage"),i={result:[]},n=new Map,a=(await Su(r,"testResult",`runId=${e}`)).data.docs;return await ne(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Ui(c,9e4);await ne(l,async d=>{if(!n.has(d.url)){let m=d.text;d.sourceUrl&&(n.set(d.url,"TEMP"),m=await vu(d.sourceUrl)),n.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,i=s([i,{result:[d]}])})},{concurrency:20}),{covUrlMap:n,mergedCoverages:i}},eh=async(r,e,t,s)=>{if(!r.collectCodeCoverage)return;wu.info("start js coverage process");let i=(0,zg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),n=Et.resolve(r.codeCoverageReportPath||"./coverage"),o=Et.resolve(n,`.js/${(0,qg.default)().format("DDMMYYYYHHmmss")}`),a=r.codeCoverageSourceMapPath?Et.resolve(r.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([dt("istanbul-lib-coverage"),YS(r.project,s)]);if(l.result.length===0){i.fail("Failed to report coverage information - js code coverage is empty");return}wu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),p={};await ne(l.result,async({url:h,functions:g})=>{let{text:b,sourceMapType:T}=d.get(h),v=await zS({sourceMapType:T,source:b,sourceMapDir:a});p[h]=v;let y=await XS(r,{source:b,sourceMap:v,functions:g});m.merge(y)}),await qS(r,o,p);let f=await JS(r,m,n,o);return i.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof x?i.fail(`${l}, missing arg: ${c.message}`):i.fail(l),wu.error(l,{err:c})}}});var rh={};z(rh,{SELENIUM_PERF_MARKS:()=>ke,SeleniumPerfStats:()=>kr});var ke,QS,kr,Ts=E(()=>{"use strict";U();ke={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},QS=["ALL",...Object.values(ke)],kr=class{constructor(){this.marks=Object.fromEntries(QS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=ce();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let s=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(s);return}this.marks[t].push(s)}getStats(){let e=Object.entries(this.marks).flatMap(([t,s])=>!Array.isArray(s)||!s.length?[]:[[`${t}_COUNT`,s.length],[`${t}_P50`,Jn(s,50)],[`${t}_P95`,Jn(s,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var oh={};z(oh,{initServer:()=>tE,mapFilesToLocalDrive:()=>Iu});function Iu(r,e){try{r.failurePath=(r.failurePath||[]).map(t=>Object.assign(t,Do[t.id]?{screenshot:Do[t.id]}:{})),Object.keys(No).forEach(t=>{r.assets||={},r.assets[nh[t]]=No[t]}),r.assets||={},r.assets.screenshots=Object.values(Do)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),r.failurePath||=[],r.assets||={},r.assets.screenshots||=[]}}async function tE({agentPort:r,agentBind:e,saveRCALocally:t}){let s=await dt("multer"),i=typeof t=="string"?t:ZS;await Eu.promises.mkdir(i,{recursive:!0});let n=s({storage:s.diskStorage({async destination(c,l,d){let m=JSON.parse(c.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let p=Bi.join(i,m.testResultId);try{await Eu.promises.mkdir(p,{recursive:!0})}catch(f){return d(f,"")}return d(null,p)},filename(c,l,d){let{fileName:m}=c.body,p=JSON.parse(c.body.metadata||"{}");if(!p.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(p.stepId){let f=Bi.extname(m);return d(null,`step_${p.stepId}_${p.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,ih.default)();o.disable("x-powered-by"),o.post("/",n.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(Do[d.stepId]=c.file.path),d.testResultId&&eE.includes(d.subType)&&(No[d.subType]||=[],No[d.subType].push(c.file.path)),l.sendStatus(200)}),o.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let d=a(o);d.listen(r,e),d.on("error",m),d.on("listening",()=>c(d.address()));function m(p){if(p.syscall!=="listen")return l(p);switch(p.code){case"EACCES":case"EPERM":return l(new x(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return l(new x(`Port ${r} is already in use`));default:return l(p)}}})}var Eu,sh,Bi,ih,ZS,Do,No,nh,eE,Ru=E(()=>{"use strict";Eu=R(require("fs")),sh=R(require("os")),Bi=R(require("path")),ih=R(require("express"));Q();Mi();ZS=Bi.join(sh.tmpdir(),"testim/rca/"),Do={},No={},nh={"test-log":"consoleLogs","har-file":"networkLogs"},eE=Object.keys(nh)});var ar,xu,ji,ah=E(()=>{"use strict";ar=R(require("lodash"));U();W();xu=A("override-test-data-builder"),ji=class{constructor(e,t,s){this.params=e;this.testInfoList=t;this.projectId=s}isObjectNotArray(e){return ar.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(e=!1){let{params:t,projectId:s}=this;return this.isObjectNotArray(t)&&t.overrideTestData!==void 0&&(this.isObjectNotArray(t.overrideTestData)&&!ar.isEmpty(t.overrideTestData)?(Object.keys(t.overrideTestData).forEach(i=>this.overrideSingleTest(i,t.overrideTestData[i])),delete t.overrideTestData):xu.error("invalid overrideTestData",{overrideTestData:t.overrideTestData,projectId:s})),this.isObjectNotArray(t)&&t.overrideAllTestsData!==void 0&&(ar.isObject(t.overrideAllTestsData)&&!ar.isEmpty(t.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,t.overrideAllTestsData)),delete t.overrideAllTestsData):xu.error("invalid overrideAllTestsData",{overrideAllTestsData:t.overrideAllTestsData,projectId:s})),this.isArrayOfObjects(t)&&e&&this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,t)),this.testInfoList}overrideSingleTest(e,t){let{projectId:s}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}xu.error("skip override test data to test name",{testName:e,projectId:s}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let s=this.mapTestListToUniqueId(e);if(s.length!==0)return this.createNewTestPerOverrideTestData(s,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return ar.chain(t).map(s=>{if(s.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(s)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:s}=this;return[...new Set(e)].map(i=>{let n=s.map(d=>this.generateTestUniqId(d)),o=n.indexOf(i),a=n.lastIndexOf(i),c=s[o],l=this.createNewTestItems(c,t);return s.splice(o,a-o+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((s,i)=>{let n=ce();return{...e,resultId:n,testData:{value:s,index:i+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function $i(r,...e){if(!(!r||typeof r!="function"))try{return await r(...e)||{}}catch(t){throw et.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var cr,et,rE,sE,iE,nE,Mo,ch=E(()=>{"use strict";cr=R(require("lodash"));U();oe();ps();hs();fe();Q();W();Mt();Ni();th();Ts();Ru();ue();pe();ah();ki();et=A("test-run-status"),rE=Er(),sE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,iE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,nE=it();Mo=class{constructor(e,t,s,i){this.testInfoList=e;this.options=t;this.branchToUse=i;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.userTestDataParams={};this.seleniumPerfStats=new kr;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData,this.userTestDataString=this.options.testDataString;let n=ii(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:Ln||t.parallel||1,browser:n,gitBranch:rE,gitCommit:sE,gitRepoUrl:iE,runnerVersion:nE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:i,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:s,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:s,projectId:i,executionId:n,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:d,testStatus:m,testCreatorName:p,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:b,testSuites:T,allLabels:v}=a,y={originalTestResultId:t,previousTestResultId:s,config:cr.cloneDeep(c),testId:l,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...y,testCreatorName:p,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:b,testSuites:T,allLabels:v},Pu({projectId:i,runId:n,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:s,testResult:y})}testStart(e,t,s,i){let n=this.getTestResult(s);return n.workerId=e,te.onTestStarted(n,e,i,s),n}async updateTestStatusRunning(e,t,s){var l;let{project:i,remoteRunId:n,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Uo(i,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){et.error("failed to upload test data artifact (runner)",{err:d})}let c=cr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,Or(i,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:n,testRetryKey:s})}async testStartReport(e,t,s){var n;if(Ze(e,this.options))return;let i=this.exportsGlobal;try{let o=await $i(this.options.beforeTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token),a=Array.isArray(this.userTestDataParams)?{}:this.userTestDataParams||{},c=(n=e.config)!=null&&n.testDataPrioritized?e.config.testData:{};return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...a,...c,...this.beforeSuiteParams,...o},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,s),e}catch(o){throw et.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,s,i,n){let o=this.testStart(e,t,s,i);return this.testStartReport(o,t,n)}onGridSlot(e,t){let s=this.getTestResult(e);s.config.gridInfo={...t,key:void 0,user:void 0},et.info("on get grid info",{gridInfo:s.config.gridInfo})}reportTestStatus(e,t,s,i){let{name:n,testId:o,testStatus:a}=s,{resultId:c,success:l}=t;if(a===Qe.EVALUATING&&Nt.isTestStatusEnabled){te.onTestIgnored(e,s,`test in ${Qe.EVALUATING} status`);return}if(l){te.onTestPassed(n);return}te.onTestFailed(s,s.failureReason,qe(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,i,c)}calcResultText(e){return e.success?ye.PASSED:ye.FAILED}onTestIgnored(e,t){let s=this.getTestResult(t);te.onTestIgnored(e,s,`test in ${Qe.QUARANTINE}`)}monitorMemoryUsage(e){let t=bl();t.isOverThreshold&&et.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,s,i,n){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=i,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&Iu(o,et),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,n),this.monitorMemoryUsage(o),te.onTestFinished(o,e,n);let c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,s,i){var o;let n=s.exportsGlobal;try{try{await $i(this.options.afterTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token)}catch(a){et.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 Or(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:s.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...i},5)}catch(a){throw et.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,s,i,n,o){let a=this.testEnd(e,t,s,i,n);return this.testEndReport(a,s,t,o)}getMobileRunSkippedReason(e,t,s){let i="",{APP_FROM_DEVICE:n,VIRTUAL_BUILD:o}=dl;return e&&(i=n),Zr(t,s)&&(i=o),i}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,s=e.company.companyId,i=(o=e.gridData)==null?void 0:o.type,n=t.map(a=>{var f,h,g,b;let c=e.browser?ai(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=es(O,i)&&oi(a.nativeApp)&&!e.appId,d=sr(e)&&(Zr(a.nativeApp,i)||l),m=Ze(a,e)||d,p={testId:a.testId,testOptimization:a.testOptimization,status:m?ye.SKIPPED:ye.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Qe.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,i)},config:{...this.execConfig,companyId:s,testData:((f=a.testData)==null?void 0:f.value)||null,testDataPrioritized:((h=a.testData)==null?void 0:h.prioritize)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((g=a.testData)==null?void 0:g.total)||null,testDataIndex:((b=a.testData)==null?void 0:b.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:c.browserValue.toLowerCase()}};return[a.resultId,p]});return Object.fromEntries(n)}async endKeepAlive(e,t,s){e==="redis"&&await _i.end(s,t),e==="mongo"&&await Ii.end(t)}async executionStart(e,t,s,i,n){et.info("execution started",{executionId:e,gridId:this.execConfig.gridId,gridHost:this.execConfig.gridHost,gridName:this.execConfig.gridName,gridType:this.execConfig.gridType,parallel:this.execConfig.parallel,runnerVersion:this.execConfig.runnerVersion,source:this.execConfig.source});let{options:o}=this,{remoteRunId:a,projectData:c,company:{companyId:l}={},slotService:d}=o;ys(()=>Promise.all([this.endKeepAlive(d,t,l),Fo("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=s||Date.now();let m={projectId:t,executionId:e,...O.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:n}},p=this.userTestDataString,f=await $i(new Function(p||""));if(f&&(this.userTestDataParams=f,Array.isArray(f))){let S=new ji(f,cr.cloneDeep(this.testInfoList),t);this.testInfoList=S.overrideTestData(!0)}let h=await $i(o.beforeSuite,m),g=new ji(h,cr.cloneDeep(this.testInfoList),t);this.testInfoList=g.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=h;let{testInfoList:b}=this,T=[],v=[],y=[];for(let S of b){if(S.isBeforeTestPlan){T.push(S);continue}if(S.isAfterTestPlan){y.push(S);continue}v.push(S)}let w=async()=>{let S=cr.cloneDeep(this.testRunStatus);await ne(Object.keys(S),async B=>{var j;let V=S[B],I=(j=V.config)==null?void 0:j.testData,k=V.testId,L=await Uo(t,k,B,I,c.defaults);L&&(delete V.config.testData,V.config.testDataUrl=L)});let C=!!(o.useLocalChromeDriver||o.useChromeLauncher),_=Au({executionId:e,projectId:t,labels:i||[],startTime:s,executions:S,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:C,intersections:o.intersections});return this.executionStartedPromise=_,_.catch(B=>et.error(B)),_};try{await w()}catch(S){et.error("Failed to start suite",{err:S}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:T,tests:v,afterTests:y}}concatSeleniumPerfMarks(e){cr.chain(e).keys().each(t=>{let s=t;this.seleniumPerfStats.marks[s]&&(this.seleniumPerfStats.marks[s]=[...this.seleniumPerfStats.marks[s],...e[s]])}).value()}async executionEnd(e){var d;let t=El(this.testRunStatus),s=t.length,i=0,n=0,o=0;for(let{status:m,testStatus:p}of t)m===ye.PASSED&&i++,m===ye.SKIPPED&&n++,m===ye.FAILED&&p===Qe.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await $i(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:s,passed:i,skipped:n})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),et.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await eh(this.options,this.branchToUse,s,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Fo("FINISHED",e,this.options.project,s===i+n+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw et.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,s,i){let n=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await Cu(e,["QUEUED"],t,s,i,this.startTime,null,this.options.project);for(let o of n){let a=this.getTestResult(o);a.status=t,a.failureReason=s,a.success=i}return this.testRunStatus}}});function ku(r){var n;let e=r.canary?"-master.zip":".zip",t=`${Zt}/testim-headless${e}`,s=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(n=r.company)==null?void 0:n.companyId,projectId:r.project,runnerEnvironment:zs});return s||(oE.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:r.resultId,executionId:r.executionId,projectId:r.project}),s=`${Zt}/testim-headless.zip`),!(r.ext||r.extensionPath)&&s&&(t=s,r.testimHeadlessExtensionDownloadUrl=s),{chrome:t,"edge-chromium":t}}function lh(r){let{chrome:e}=ku(r);return e}function Bo(r){let e=`${Zt}/sessionPlayer`;return r.canary?`${e}-master`:e}var oE,Wi=E(()=>{"use strict";ue();pe();W();oE=A("runOptionsUtils")});function ws(r){var i;let t=(i=new RegExp(`^\\b(${Object.values(Ou).join("|")})`).exec(r))==null?void 0:i[0];return t||Ou[em]||"usw2"}var Ou,ph,jo=E(()=>{"use strict";ue();Ou={"us-west-2":"usw2","eu-central-1":"euc1"},ph=Object.fromEntries(Object.entries(Ou).map(([r,e])=>[e,r]))});function dh(r,e){if(e){if(!dE.has(e)){Vi.warn(`OS ${e} is not supported by LT`,{testResultId:r});return}return e}}var mh,fh,qt,gh,hh,yh,$o,bh,Vi,aE,cE,Gi,lE,uE,pE,Kt,dE,Wo=E(()=>{"use strict";mh=R(require("ms")),fh=R(require("p-retry")),qt=R(require("node:os")),gh=R(require("portfinder")),hh=R(require("node:child_process"));U();We();fe();yh=R(require("node:fs")),$o=R(require("node:fs/promises")),bh=require("node:path");Q();W();Wi();oe();pe();U();jo();Vi=A("lambdatestService"),aE="https://downloads.lambdatest.com/tunnel/v3",cE={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"},Gi=`${qt.tmpdir()}/LT`,lE=`${Gi}/LT`,uE=(0,mh.default)("15m"),pE="2560x1440",Kt=class r{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===N.TESTIM_LAMBDATEST||e.type===N.LAMBDATEST||e.type===N.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t,s){if(r.isLambdatestGrid(e)&&(r.lambdatestConfigPromise||=_u(t,s),r.lambdatestConfig=await r.lambdatestConfigPromise,this.isActive=!0,s))try{let i=await Promise.resolve().then(()=>(fe(),we));this.smartUIIntegrationData=await i.getVisualTestingIntegrationData(s,"lambdatest")}catch{}}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?uE:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await Te(lE))return;let t=cE[qt.platform()+qt.arch()];if(!t)throw new Error(`tunnel on ${qt.platform()+qt.arch()} platform is not supported.`);let s=`${Gi}.zip`;await Xe(`${aE}/${t}`,s),await Ye(s,Gi)}static async chmodLtTunnel(e){if(!(qt.platform()==="win32"||!await Te(e))){try{await $o.access(e,yh.constants.X_OK);return}catch{}try{await $o.chmod(e,"777")}catch(s){throw Vi.error("Failed to make LT tunnel executable",{e:s}),s}}}static async delay(e){await ie(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){r.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await gh.getPortPromise(),{gridData:s={},gridUsername:i,gridPassword:n,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;r.tunnelName=ce();let l=["--tunnelName",r.tunnelName,"--infoAPIPort",String(t)];if(O.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],o&&a)l=[...l,"--ntlm-username",o,"--ntlm-password",a];else{let p=JSON.parse(O.flags.addCustomLTtunnelNTLMOptions.getValue());p&&(l=[...l,...hl(p)])}if(O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,*.betterstackdata.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),s.tunnelUser&&s.tunnelKey)l=[...l,"--user",s.tunnelUser,"--key",s.tunnelKey];else if(i&&n)l=[...l,"--user",i,"--key",n];else throw new x("tunnel requires username and password");if(c)try{let p=new URL(c);l=[...l,"--proxy-host",p.hostname],p.port&&(l=[...l,"--proxy-port",p.port]),p.username&&p.password&&(l=[...l,"--proxy-user",p.username,"--proxy-pass",p.password])}catch{throw new x("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await r.delay(3e3),await r.chmodLtTunnel((0,bh.join)(Gi,"LT")),r.tunnel=hh.spawn("./LT",l,{cwd:Gi});let d="",m="";r.tunnel.stdout.on("data",p=>{d+=p.toString()}),r.tunnel.stderr.on("data",p=>{m+=p.toString()});try{let p=await(0,fh.default)(()=>Ee(`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});Vi.info("LT tunnel info",p)}catch(p){throw Object.assign(p,{stdoutResult:d,stderrResult:m}),Vi.error("Failed to start LT tunnel",{err:p}),p}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!r.tunnel))return new Promise((t,s)=>{r.tunnel.on("close",i=>{i&&s(new Error(`tunnel process exited with code ${i}`)),t()}),r.tunnel.kill()})}getCapabilities(e,t,s,i,n,o,a,c){var _,B;if(!this.isActive)return{};let l=r.lambdatestConfig.CAPABILITIES[t]||{},d={...r.tunnelName&&{tunnel:!0,tunnelName:r.tunnelName}},m=[],{canary:p,ext:f,extensionPath:h,installCustomExtension:g}=e,b={platform:dh(i,a==null?void 0:a.os)||dh(i,(_=o==null?void 0:o.lt)==null?void 0:_.platform)||l.platform||r.lambdatestConfig.PLATFORM,resolution:r.lambdatestConfig.RESOLUTION??pE,...t!=="safari"&&{version:l.version}};if(c!==J.APPIUM&&c!==J.SELENIUM&&!f){let V=ku({canary:p});!h&&V[t]&&(m=[...m,V[t]]),h&&De(h)&&(m=[...m,h]),!m.length&&!h&&Vi.warn("No extension was loaded in LambdaTestService",{extUrls:V,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&De(g)&&(m=[...m,g]);let T=ws(e.project||""),y={euc1:"eu"}[T],w=y?{region:y}:{},S=(B=this.smartUIIntegrationData)!=null&&B.projectToken?{smartUI:{project:this.smartUIIntegrationData.projectToken,build:s}}:{};return{"LT:Options":{build:s,name:`${i} - ${n}`,...w,selenium_version:r.lambdatestConfig.SELENIUM_VERSION,timezone:r.lambdatestConfig.TIMEZONE,...l,...b,loadExtension:m,...d,...S,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}},dE=new Set(["Linux","Windows 10","Windows 11","MacOS Tahoe","MacOS Sequoia","macOS Sonoma","macOS Ventura","macOS Monterey","macOS Catalina","macOS Big Sur","macOS Mojave","macOS High Sierra","macOS Sierra","OS X El Capitan","OS X Yosemite","OS X Mountain Lion"])});var Th,mE,Vo,Lu=E(()=>{"use strict";Q();Th=["platformName","platform","app","bundleId","appPackage","extensions"],mE=["selenium_version","protocol","host","port","path","build"],Vo=(r,e)=>{let t=e==="lambdaTest"?[...Th,...mE]:Th,s=[],i=[r];for(;i.length;){let n=i.pop();for(let[o,a]of Object.entries(n))t.includes(o)&&s.push(o),a&&typeof a=="object"&&i.push(a)}if(s.length)throw new x(`Custom capabilities contains forbidden keys: ${s.join(", ")}`)}});function gE(r,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(r.desiredCapabilities,t),r}function kh(r){return Rh.readFileSync(r,{encoding:"base64"})}function Oh(r,e,t,s){if(t!=null&&t.isLambdatestRun()&&De(r))return null;if(r){if(s)return r.endsWith(".zip")?(Ye(r,Sh),Sh):r;let i=kh(r);Ss.info(`adding extension: custom, path: ${r} length: ${i.length} hash: ${Mu(i)} current extension count: ${e.length}`),e.push(i)}return null}function _h(r,e,t,s,i,n){if(i!=null&&i.isLambdatestRun())return null;let o=r.testimHeadlessExtensionDownloadUrl;if((r.ext||s)&&!o){let m=typeof r.ext=="string"?r.ext:`${__dirname}/..`,p=s||m,f=`--load-extension=${p}`;return Ss.info(`adding extension: testim unpacked , path: ${p}`),t.push(f),null}let c=`testim-headless${r.canary?"-master.zip":".zip"}`;!r.extensionPath&&o&&(c=_r.basename(o));let l=_r.join(process.cwd(),c);if(n)return Ye(l,vh),vh;let d=kh(l);return Ss.info(`adding extension: testim zipped, path: ${l} length: ${d.length} hash: ${Mu(d)} current extension count: ${e.length}`),e.push(d),null}function hE(r,e,t,s,i,n,o,a){var g,b;let c=t.seleniumName||t.browserValue,l=[],d=[...Ah];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Du.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Du.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(Nu(i)){let T=O.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),m.prefs["download.default_directory"]="C:\\Users\\testnode",r.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),r.desiredCapabilities["aws:maxDurationSecs"]=2400,r.desiredCapabilities["aws:idleTimeoutSecs"]=60}Nu(i)&&c==="MicrosoftEdge"&&(r.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`));try{let T=Go();T.length&&T.forEach(v=>d.push(`--disable-features=${v}`))}catch{}e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Du.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(b=(g=e.projectData)==null?void 0:g.defaults)!=null&&b.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(r.desiredCapabilities,{browserName:c});function p(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+ul.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}p(),Oh(s,l,o),a===J.EXTENSION&&_h(e,l,d,n,o),l.length>0&&(m.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[c],h={MicrosoftEdge:"ms",chrome:"goog"}[c];return Kt.isLambdatestGrid(i)&&delete m.w3c,e.oldCapabilities&&i.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(r.desiredCapabilities[f]=m),(e.w3cCapabilities||i.type==="testimEnterprise")&&(r.desiredCapabilities[`${h}:${f}`]=m),r}function bE(r,e,t){let s={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(s,{"browser.helperApps.neverAsk.saveToDisk":Eh.join(","),"browser.helperApps.neverAsk.openFile":Eh.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(r.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:s}},t!=null&&t.isLambdatestRun()?{"LT:Options":{enableCustomTranslation:!0}}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(r.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(r.desiredCapabilities["moz:firefoxOptions"].args||(r.desiredCapabilities["moz:firefoxOptions"].args=[]),r.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),r}function vs(r){return`${r.width}x${r.height}`}function IE(r){let{platform:e}=r;if(!e)return vs(Ih);let t=e.split(" ")[1];return e.startsWith("Windows")&&EE.has(t)?vs(wE):e==="Linux"?vs(TE):e.startsWith("macOS")?vs(vE):vs(e==="OS X El Capitan"||e==="OS X Yosemite"?SE:Ih)}function RE(r,e,t){let{saucelabs:s}=r;if(s!=null&&s.browserVersion&&(s.version=s.browserVersion),s!=null&&s.username&&s.accessKey){let i={"sauce:options":{name:e}};if(i["sauce:options"].screenResolution=IE(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version;let n=s.appiumVersion||t.sl.appiumVersion;n&&(i["sauce:options"].appiumVersion=n);let o=["screenResolution","appiumVersion"];t.browserValue!=="safari"&&o.push("safari_version");let a=Ve.omit((0,Ch.cloneDeep)(t.sl),o);return Ve.merge(a,i,s)}return Ve.merge(i,s)}return{}}function xE(r){let{runnerOptions:e}=r;if(Ve.isEmpty(e.browserstack))return{"bstack:options":{}};let{projectData:t,testRunConfig:s,testId:i,testName:n,executionId:o,executionName:a}=r,{"browserstack.user":c,"browserstack.key":l,...d}=e.browserstack,m={"bstack:options":{buildName:`${a} - ${o}`,sessionName:`${n} - ${i}`,projectName:`${t.name} - ${t.projectId}`,...d,...c?{userName:c}:{},...l?{accessKey:l}:{}}};return s&&s.browserValue==="safari"&&s.bs.safari_version&&(m["bstack:options"].os_version=s.bs.safari_version,s.bs.safari_version==="10"&&Object.assign(m["bstack:options"],{"safari.options":{technologyPreview:!0}})),m}function CE(r){return r.perfecto?r.perfecto:{}}function AE(r,e,t){if(r.experitestToken){let s=e==="safari";return{accessKey:r.experitestToken,browserVersion:"latest",platformName:s?"MAC":"WIN10",seleniumScreenshot:s,newSessionWaitTimeout:t}}return{}}function PE(r,e={}){let{gridData:t={},gridUsername:s,gridPassword:i}=r,n=s||t.user||e.user,o=i||t.key||e.key,a={};return n&&o&&(a.Authorization=xc(n,o)),a}function Go(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(r=>r.trim().length)}function Ho(r){var B,V,I,k;let{overrideConfiguration:e,browserOptions:t,testId:s,testName:i,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:d,testResultId:m,lambdatestService:p,mode:f,customCapabilities:h,useLocalChromeDriver:g}=r;if(o.mode==="local"){let L=[],j=[...Ah],G={};t.headless&&j.push("--headless"),t.silentDebuggerExtensionApi&&j.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&j.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let se=Go();se.length&&se.forEach(he=>j.push(`--disable-features=${he}`))}catch{}t.chromeExtraArgs&&t.chromeExtraArgs.forEach(se=>j.push(`--${se}`)),t.chromeBinaryLocation&&(G.binary=t.chromeBinaryLocation);let K,q=null;return f!==J.SELENIUM&&(K=_h(t,L,j,null,p,g)),q=Oh(a,L,p,g),g&&j.push("--enable-unsafe-extension-debugging","--remote-debugging-pipe"),{logLevel:wh,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:j,extensions:L,...G},browserName:"chrome",...g&&{webSocketUrl:!0}},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515,...g&&K&&{unzippedTestimExtensionPath:K},...g&&q&&{unzippedCustomExtensionPath:q}}}let{driverRequestTimeout:b,driverRequestRetries:T}=t,v=PE(t,o),y={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:wh,connectionRetryTimeout:b,connectionRetryCount:T,getSessionTimeout:Math.max(p.getSessionTimeout,t.getSessionTimeout),getSessionRetries:p.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0},...!Ve.isEmpty(v)&&{headers:v},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};if(Nu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,y.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(y.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key),o.type==="local"){let L=new URL(o.host.startsWith("http")||o.host.startsWith("https")?o.host:`${o.protocol}://${o.host}`);y.user=L.username,y.key=L.password,y.hostname=L.hostname,y.host=L.hostname}let w=Number(t.browserTimeout/1e3),S=t.browser||(n==null?void 0:n.browserValue),C={runnerOptions:t,testId:s,testName:i,testRunConfig:n,executionId:c,executionName:l,projectData:d};Ve.merge(y.desiredCapabilities,RE(t,i,n),xE(C),CE(t),AE(t,S,w),p==null?void 0:p.getCapabilities(t,S,c,m,i,n,e,f));let _=null;switch(!t.ext&&!t.extensionPath&&((B=o.host)!=null&&B.endsWith(".testim.io"))&&!t.canary&&f===J.EXTENSION&&(S==="chrome"||S==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(_="/opt/testim-headless"),S){case"chrome":case"edge-chromium":y=yE(y,t,n,a,o,_,p,f);break;case"firefox":y=bE(y,t,p);break;case"safari":case"safari technology preview":y=gE(y,S);break;default:break}h?(Vo(h,o.type),Ve.merge(y.desiredCapabilities,h)):Ve.merge(y.desiredCapabilities,t.seleniumCapsFileContent);try{let L={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},j=se=>se[o.provider]||se[y.host]||se[L[y.host]],G=se=>{var he,ze;return j(se)||se[(he=y.desiredCapabilities)==null?void 0:he.browserName]||se[(ze=y.desiredCapabilities)==null?void 0:ze.version]||se||{}},K=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),q=G(G(K));Object.keys(q).length&&(Ss.info(`Adding custom capabilities: ${JSON.stringify(q)}`),Object.assign(y.desiredCapabilities,q))}catch(L){Ss.error("Failed to load custom capabilities",{error:L,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(y.desiredCapabilities&&!y.capabilities&&(fE(y),y.capabilities={alwaysMatch:y.desiredCapabilities,firstMatch:[{}]},delete y.desiredCapabilities),y.capabilities||={alwaysMatch:{},firstMatch:[{}]},y.capabilities.alwaysMatch||={},y.capabilities.alwaysMatch["wdio:enforceWebDriverClassic"]=!0,y.hostname=y.host,r.printFinalCaps){let L=(V=y.capabilities)==null?void 0:V.alwaysMatch,j=JSON.parse(JSON.stringify(y)),G=(I=j==null?void 0:j.capabilities)==null?void 0:I.alwaysMatch,K=se=>se.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(se=>{var he,ze;G!=null&&G[se]&&(G[se].extensions=(ze=(he=L==null?void 0:L[se])==null?void 0:he.extensions)==null?void 0:ze.map(K))}),G!=null&&G.loadExtension&&(G.loadExtension=(k=L==null?void 0:L.loadExtension)==null?void 0:k.map(K));let q=require("node:util");console.log(q.inspect(j,{showHidden:!1,depth:null,colors:!0}))}return y}var Rh,_r,xh,Ve,Ch,Ss,wh,Du,Ah,Ph,vh,Sh,Mu,Nu,fE,yE,Eh,Ih,TE,wE,vE,SE,EE,zo=E(()=>{"use strict";Rh=R(require("node:fs")),_r=R(require("node:path")),xh=R(require("node:crypto")),Ve=R(require("lodash"));U();ue();W();cl();U();pe();oe();Wo();Lu();Ch=require("lodash"),Ss=A("testim-desired-capabilities-builder"),wh=_n?"debug":"silent",Du={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Ah=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],Ph=_r.join(Tt,"extensions"),vh=_r.join(Ph,"testim-headless"),Sh=_r.join(Ph,"custom-extension"),Mu=(...r)=>xh.createHash("sha256").update(r.join("")).digest("hex"),Nu=r=>r.type===N.DEVICE_FARM||r.type===N.HYBRID&&r.provider==="devicefarm",fE=r=>{var s;let{desiredCapabilities:e}=r;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),((s=e["goog:chromeOptions"])==null?void 0:s.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in r.desiredCapabilities&&(r.user=r.desiredCapabilities.username,delete r.desiredCapabilities.username),"accessKey"in r.desiredCapabilities&&(r.key=r.desiredCapabilities.accessKey,delete r.desiredCapabilities.accessKey);let t;try{t=O.flags.unsupportedCapsFields.getValue();let i=JSON.parse(t);if(!Array.isArray(i))return;i.forEach(n=>{delete e[n]})}catch{Ss.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};yE=Ve.memoize(hE,(r,e,t,s,i,n)=>{let o=JSON.stringify(r.desiredCapabilities),a=JSON.stringify(Ve.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(i.type);return Mu(o,a,c,s,l,n)}),Eh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Ih={width:1920,height:1080},TE={width:1920,height:1200},wE={width:2560,height:1600},vE={width:2360,height:1770},SE={width:2048,height:1536},EE=new Set(["7","8","8.1","10","11"])});function Ft(r){var e,t,s,i,n,o,a,c;return((e=r.message)==null?void 0:e.match(/Command not found/))||r.message==="HTTP method not allowed"||((t=r.message)==null?void 0:t.toLowerCase())==="unknown error"||((s=r.message)==null?void 0:s.match(/Unknown timeout type/))||r.name==="unknown command"||((i=r.message)==null?void 0:i.match(/did not match a known command/))||((n=r.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=r.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=r.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((c=r.message)==null?void 0:c.match(/\.\w* is not a function/))}function Dh(r,e,t){if(!e||!r)return r;if(r.includes("%"))return r.replace(/ /g,"%20");try{return decodeURI(r)!==r?r:encodeURI(r)}catch(s){return t&&t.warn("tried to encode url but failed",{err:s,url:r}),r}}var Fu=E(()=>{"use strict"});function Uu(r){function e(p){return p?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(p.nodeType):!1}function t(p){return p?s(p.parentNode,e):null}function s(p,f){for(let h=p;h&&h!==p.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function i(p,f){for(let h=p;h&&h!==p.ownerDocument;h=t(h))if(f(h))return h;return null}function n(p,f){if(!p||!f)return null;p instanceof DocumentFragment&&(p=p.host);let g=window.getComputedStyle(p).getPropertyValue(f);if(g&&g!=="inherit")return g;let b=t(p);return n(b,f)}function o(p){let f=p.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(p.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=n(p,"stroke-width");return!!g&&parseInt(g,10)>0}return n(p,"overflow")==="hidden"?!1:Array.from(p.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(p){return n(p,"overflow")==="hidden"}function c(p){return!p||!a(p)||!p.childNodes.length?!1:Array.from(p.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:c(f))}function l(p){var f;return p?(f=p.parentNode)!=null&&f.host?!0:l(p.parentNode):!1}if(!r||!l(r)&&!document.contains(r))return!1;switch(r.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=s(r,h=>h.tagName.toUpperCase()==="SELECT");return Uu(f)}case"INPUT":if(r.type==="hidden")return!1;break;default:break}if(n(r,"visibility")!=="visible")return!1;let d=!!i(r,p=>Number(n(p,"opacity"))===0),m=!!i(r,p=>n(p,"display")==="none");return!(d||m||!o(r)||c(r))}var Nh=E(()=>{"use strict"});var Mh,Fh,Ut,kE,OE,qo,Uh=E(()=>{"use strict";Mh=R(require("promise-queue")),Fh=R(require("webdriverio"));ue();je();U();W();Gr();Nh();Fu();Ts();Ut=A("WebDriverApi"),kE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},OE={implicit:0,pageLoad:1,script:2},qo=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}rejectWithLog(e,t){let{testName:s,testResultId:i}=this,n=t?t.toString().slice(0,2e3):"";throw Ut.warn("error from selenium",{err:e,testResultId:i,testName:s,crashingFunc:n}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),kc!==void 0&&(e=kc);let t=1/0;this.queue=new Mh.default(e,t)}async addToQueue(e){var s,i;let t=(s=this.seleniumPerfStats)==null?void 0:s.markStart();try{return await this.queue.add(e)}catch(n){return this.rejectWithLog(n,e)}finally{(i=this.seleniumPerfStats)==null||i.markEnd(t)}}async installExtensions(e){var s;let t=[e==null?void 0:e.unzippedTestimExtensionPath,e==null?void 0:e.unzippedCustomExtensionPath].filter(Boolean);for(let i of t)await((s=this.client)==null?void 0:s.send({method:"webExtension.install",params:{extensionData:{type:"path",path:i}}}))}async initClient(e,t,s,i,n){var c,l,d,m,p,f,h,g;this.testName=t,this.testResultId=s,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let o=((c=e.capabilities.alwaysMatch)==null?void 0:c.loadExtension)||((l=e.capabilities.alwaysMatch)==null?void 0:l.loadExt)||((f=(p=(m=(d=e.capabilities.alwaysMatch)==null?void 0:d["goog:chromeOptions"])==null?void 0:m.extensions)==null?void 0:p[0])==null?void 0:f.slice(0,80)),a=(h=this.seleniumPerfStats)==null?void 0:h.markStart(ke.GET_BROWSER);try{await this.addToQueue(async()=>{Ut.info("requesting browser",{testResultId:s,testName:t,extUrl:o}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=s??"",this.client=await Fh.remote(e),this.client.on("dialog",async b=>{try{await b.accept()}catch{}}),i&&await this.installExtensions(n),this.logGridStatus(s)}),M("after client init")}finally{(g=this.seleniumPerfStats)==null||g.markEnd(a,ke.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,s="N/A",i="N/A",n;try{n=await this.client.status();for(let a of n.nodes||[])for(let c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){s=a,i=c;break}}catch(a){if(a.message==="unknown error"){Ut.info("grid status is not supported by the grid",{testResultId:e});return}Ut.error("failed to get grid status",{error:a,testResultId:e});return}s&&typeof s=="object"&&"slots"in s&&(s==null||delete s.slots),Ut.info("grid status",{gridStatusMsg:n.message,ready:n.ready,browserNode:s,gridSlot:i,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let i=a=>{throw Object.assign(a,{executedScript:e}),a},n=()=>this.client.execute(e,t).catch(i),o=()=>this.client.executeScript(e,t).catch(i);if(this.unsupportedActions.has("execute"))return n();t=t.map(a=>{if(a===null){Ut.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(Ft(a))return this.unsupportedActions.add("execute"),n();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let i=()=>this.client.execute(e,...t),n=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return i();try{return await n()}catch(o){if(Ft(o))return this.unsupportedActions.add("executeAsync"),i();throw o}})}}async executeCDP(e,t={}){var i;if(!this.isChromium())return;let s=await((i=this.client)==null?void 0:i.sendCommandAndGetResult(e,t));return s!=null&&s.targetInfos?s.targetInfos:[]}async takeScreenshot(){var t,s;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(ke.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.takeScreenshot()})}}finally{(s=this.seleniumPerfStats)==null||s.markEnd(e,ke.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(ke.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Fe(e)))}finally{this.seleniumPerfStats.markEnd(t,ke.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(async()=>{var s;return(s=this.client)==null?void 0:s.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(i=>({value:i})),s=()=>this.execute(Uu,{ELEMENT:e,[Qt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return s();try{return await t()}catch(i){if(Ft(i))return this.unsupportedActions.add("elementIdDisplayed"),s();throw i}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Dh(e,this.isSafari(),Ut))})}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 s=()=>{let n=[];return n[OE[e]]=t,this.client.setTimeouts(...n)},i=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return i();try{return await s()}catch(n){if(Ft(n))return this.unsupportedActions.add("timeouts"),i();throw n}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let s=function(i,n){window.scrollTo(i,n)};return this.execute(s,e,t)}async setValue(e,t){return await this.elementIdClear(Fe(e)),await this.elementIdValue(Fe(e),t)}async getViewportSize(e){let t=await this.execute(kE);if(typeof e=="string"&&/(width|height)/.test(e)){let s=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[s]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let s=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.elementSendKeys(e,s)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitFormManually(e){return this.addToQueue(async()=>{var n;let t=(n=this.client)==null?void 0:n.$(e),s=t.$('button[type="submit"]');return await s.isExisting()?s.click():t.$("input:last-of-type").keys("Enter")})}async findElementAndPress(e,t,s){let i;try{i=await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:s})})}catch(n){if(n.message.includes("unexpected alert open")||n.message.includes("dialog detected"))await this.alertAccept().catch(o=>Ut.warn("failed to click on alert",{err:o})),i=await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:s})});else throw n}return{value:i}}_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 s;return(s=this.client)==null?void 0:s.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).dragAndDrop(t)})}}moveTo(e,t,s){let i={...typeof t=="number"&&{xOffset:t},...typeof s=="number"&&{yOffset:s}};return this.isSafari()&&!Object.hasOwn(i,"yoffset")&&(i.yOffset=1),this.isSafari()&&!Object.hasOwn(i,"xoffset")&&(i.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let n=this.client.$(e);await this.client.action("pointer").move({origin:n}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.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 s=async()=>await this.client.getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),n=Math.abs(e.height);s=async()=>await this.client.setWindowSize(i,n)}try{return await s()}catch(i){throw i}})}}setCookie(e,t,s,i,n,o,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:s,httpOnly:i,secure:n,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var s;return(await((s=this.client)==null?void 0:s.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayed()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchFrame(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,s;await((s=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:s.call(t)),e(!0)})}catch(e){Ut.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.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 s;return(s=this.client)==null?void 0:s.isAppInstalled(e)});return Ut.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 lr={};z(lr,{getSessionPlayer:()=>ee,options:()=>ju});var Ko,ju,Bu,ee,ve=E(()=>{"use strict";Ko=require("path");W();ju={playerPath:void 0},ee=()=>{if(Bu)return Bu;let r=(je(),Ue(Be));r.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(gi(),Ue(fi)),t=e(),s=ju.playerPath?(0,Ko.resolve)(ju.playerPath,"src/background/sessionPlayerInit.ts"):(0,Ko.join)(t,"sessionPlayer.js"),i=require(s);return r.log("getSessionPlayerRequire end"),Bu=i,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&i.setLoggerFormatter&&i.setLoggerFormatter(Lm),i}});var Bh={};z(Bh,{doubleClick:()=>_E});var _E,jh=E(()=>{"use strict";_E=function(r,e){let t=["pointerup","pointerdown","pointermove"],s=getLocatedElement(r.locatedElement);if(!s)throw new Error("element not found");let i=r.events,n={status:"done",success:!0};window.__unloadNavigator=function(){e(n)};let o=function(p){function f(v,y,w){return w>v&&w<y}let h=p.pointerPosition||{},g=s.getBoundingClientRect(),b=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:b,y:T}},a=function(p,f){return{screenX:0,screenY:0,clientX:p,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(p,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(p,g)},l=function(p,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(p,!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 p=document.activeElement;for(;(f=p.shadowRoot)!=null&&f.activeElement;)p=p.shadowRoot.activeElement;return p},m=function(p){let f=o(p),h=p.event;return t.includes(h)?c(h,f.x,f.y):l(h,f.x,f.y)};try{i.map(f=>m(f)).filter(Boolean).forEach(f=>s.dispatchEvent(f));let p=d();dispatchFocus(r.elementToFocusLocatedElement,p),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(n)}catch(p){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:p.toString(),success:!1})}}});var Hi={};z(Hi,{dispatchFocus:()=>LE});function LE(r,e){function t(n){let o=document.createEvent("HTMLEvents");return o.initEvent(n,!0,!1),o}function s(){var o;let n=document.activeElement;for(;(o=n.shadowRoot)!=null&&o.activeElement;)n=n.shadowRoot.activeElement;return n}function i(n,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),n.dispatchEvent(t("focusin")),n.dispatchEvent(t("focus")),typeof n.focus=="function"&&n.focus();let a=s();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(r){let n=getLocatedElement(r);if(n&&n!==e)try{i(n,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var zi=E(()=>{"use strict"});var Hh={};z(Hh,{WebDriver:()=>Dr});async function FE(r){var e,t;try{let s=(t=(e=r==null?void 0:r.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return s?await NE(s):void 0}catch(s){Ge.info("Error getting cdpAddress",s);return}}var Is,Vh,Gh,Ge,Es,DE,$h,NE,Lr,ME,Wh,qi,Dr,Ki=E(()=>{"use strict";Is=R(require("lodash"));U();je();zo();Vh=R(require("p-retry")),Gh=R(require("ua-parser-js"));Gr();W();Fu();Uh();Q();pe();Ts();Ge=A("webdriver"),[Es,DE]=[0,2],{extractElementId:$h,getCdpAddressForHost:NE}=Y,Lr=()=>(ve(),Ue(lr)).getSessionPlayer().codeSnippets,ME=()=>(ve(),Ue(lr)).getSessionPlayer().locatorBuilderUtils,Wh=()=>(ve(),Ue(lr)).getSessionPlayer().utils,qi=()=>(ve(),Ue(lr)).getSessionPlayer().positionUtils;Dr=class extends qo{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.keepAliveFailedCallbacks=[];this.generalKeepAliveFailures=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null)}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(s=>s!==t)}registerToKeepAliveFailed(t){this.keepAliveFailedCallbacks.push(t)}unregisterToKeepAliveFailed(t){this.keepAliveFailedCallbacks=this.keepAliveFailedCallbacks.filter(s=>s!==t)}async init(t){var B,V,I,k,L,j,G,K;let{projectData:s,overrideConfiguration:i,browserOptions:n,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:p,testResultId:f,seleniumPerfStats:h,fastInit:g,lambdatestService:b,printFinalCaps:T,mode:v,customCapabilities:y,useLocalChromeDriver:w}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=!!((I=(V=(B=n==null?void 0:n.company)==null?void 0:B.activePlan)==null?void 0:V.premiumFeatures)!=null&&I.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let S=Ho({projectData:s,browserOptions:n,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:p,testResultId:f,lambdatestService:b,overrideConfiguration:i,printFinalCaps:T,mode:v,customCapabilities:y,useLocalChromeDriver:w});S.desiredCapabilities&&delete S.desiredCapabilities.marionette,S.capabilities&&delete S.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(b==null?void 0:b.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=h;let C=g?0:1500,_=g?(()=>null):()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let q={unzippedTestimExtensionPath:S.unzippedTestimExtensionPath,unzippedCustomExtensionPath:S.unzippedCustomExtensionPath},se=await this.initClient(S,a,f,w,q);M("after initResult before getCdpAddress in init"),this.cdpUrl=await FE(se),M("after getCdpAddress in webdriver.js init"),Ge.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await ie(C),O.flags.dontFocusOnInit.isEnabled()||await _(),M("after focus and delay in webdriver.js init")}catch(q){let se=JSON.stringify(Is.omit(S,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Ge.error("failed to init webdriver",{err:q,capabilitiesAsString:se});let he=((L=(k=n==null?void 0:n.company)==null?void 0:k.activePlan)==null?void 0:L.plan)==="free";throw(j=q.stack)!=null&&j.includes("at startWebDriverSession")&&((G=q.message)!=null&&G.startsWith("Failed to create session"))&&((K=q.message)!=null&&K.includes("Timeout awaiting 'request'"))&&he?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(q.message)?new qr(q.message):/capabilit(y|ies)/.test(q.message)&&!/UND_ERR_HEADERS_TIMEOUT/.test(q.message)?new Fn(q.message):/403 Forbidden/.test(q.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(q.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${q.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=n=>Is.zip(n.slice(0,-1),n.slice(1)),s=this._keepAliveRequests.map(({start:n})=>n).filter(Boolean),i=t(s).map(([n,o])=>o-n);return Math.max(...i)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(i=>t.message.includes(i))}start(){if(this.started)return;this.started=!0;let t=async()=>{let s=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),i=(a,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function n(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=ce();s(o);try{await this.executeJS(n),this._isAlive=!0,i("end",o),this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0}catch(a){if(i("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,Ge.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Ge.warn("failed to click on alert",{err:c}));return}if(Ge.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Ge.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.handleThresholdBasedError(this.browserClosedCallbacks,a)}else this.generalKeepAliveFailures++,this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures>=3&&this.handleThresholdBasedError(this.keepAliveFailedCallbacks,a)}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}handleThresholdBasedError(t,s){t.forEach(i=>{try{i(s)}catch{}})}async switchToLocatedFrame(t){let s=await this.getElement(t);if(!s.value)throw new Error("Element not found");let i=$h(s.value);return await this.switchFrame({ELEMENT:i,[Qt]:i}),s}switchFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(s){throw(t=s.message)!=null&&t.includes("ECONNREFUSED")?new Un:s}}async getElement(t){var n;let s=this.seleniumPerfStats.markStart(ke.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(s,ke.GET_ELEMENT)}if(((n=t==null?void 0:t.shadowPath)==null?void 0:n.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
19
19
|
var fn = ${Lr().getLocatedElementCode};
|
|
20
20
|
return fn.apply(null, arguments);
|
|
21
21
|
`,t)}finally{this.seleniumPerfStats.markEnd(s,ke.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(s,ke.GET_ELEMENT)}}executeJS(t,...s){return this.execute(t,...s)}async executeCodeAsync(t,s,...i){return await this.timeouts("script",s),await this.executeAsync(t,...i)}async markDynamicParent(t,s){function i({attributeName:n,attributeValue:o,locatedElement:a}){let c=getLocatedElement(a);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(n,o)}await this.executeJS(`
|