@testim/testim-cli 4.186.8 → 4.187.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.js +80 -80
- package/cli.js.map +4 -4
- package/npm-shrinkwrap.json +273 -242
- package/package.json +3 -4
package/cli.js
CHANGED
|
@@ -1,56 +1,56 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
${c.msg}`));for(let m of
|
|
4
|
-
${c.msg}`));for(let p of lv)o[p]instanceof Error&&(c[p]={message:o[p].message,stack:o[p].stack,name:o[p].name,type:o[p].type,cause:o[p].cause,...o[p]});Object.keys(c).length>0&&(i&&!m&&(c.msg=i),Object.assign(d,c)),this.logger.addLog(d),t(null,!0)}setProxy(e){this.proxy=e}async waitForFlush(){return await this.logger.waitForFlush()}}});var Dm={};q(Dm,{featureFlagsService:()=>O});var F,Om,_m,Lm,uv,pv,dv,km,Fi,jc,O,ue=I(()=>{"use strict";F=R(require("rox-node")),Om=R(require("node-fetch")),_m=require("eventsource");W();U();le();Lm=A("FeatureFlagsService"),uv=!Ue&&!0&&!dm,pv=2e4,dv=3600*24,km=["labs","disabled","enabled"],Fi=class extends F.default.RoxString{constructor(e="disabled"){super(e,km)}getValue(){let e=super.getValue();return km.includes(e)?e:(Lm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},jc=class{constructor(){this.flags={useNewWSCLI:new F.default.Flag,useSafariWebdriverVisibilityChecks:new F.default.Flag,useClickimVisibilityChecks:new F.default.Flag,runGetElementCodeInAut:new F.default.Flag,enableFrameSwitchOptimization:new F.default.Flag,maximumJsResultSize:new F.default.RoxNumber(2e3*1024),skipFileInputClicks:new F.default.Flag,errorMessageOnBadNetwork:new F.default.Flag(!0),warnOnBadNetwork:new F.default.Flag(!1),overrideAzureStorageUrl:new F.default.Flag,autoSaveDownloadFileFireFox:new F.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new F.default.Flag(!0),experimentalPreCodeCompilation:new F.default.Flag(!0),experimentalAsyncCustomCode:new F.default.Flag,useSameBrowserForMultiTests:new Fi("labs"),highSpeedMode:new Fi,usePortedHtml5DragDrop:new F.default.Flag,testNamesToBeforeSuiteHook:new F.default.Flag,addCustomCapabilities:new F.default.RoxString("{}"),addCustomLTtunnelNTLMOptions:new F.default.RoxString("{}"),LTNetworkCapabilities:new F.default.Flag,downloadToBase64:new F.default.Flag,publicGridURL:new F.default.RoxString("public-grid.testim.io"),allowAppFromDeviceRuns:new F.default.Flag(!0),unsupportedCapsFields:new F.default.RoxString("[]"),dontFocusOnInit:new F.default.Flag,retryOnSeleniumHubError:new F.default.Flag,enableLambdaTestTunnelNTLM:new F.default.Flag,enableLambdaTestTunnelSkipUpgrade:new F.default.Flag,tdcHsPreventNetworkCapture:new F.default.Flag,enableBatchTDC:new F.default.Flag,clearRunnerFileCache:new F.default.Flag,forceTurboModeIfNeeded:new F.default.Flag,redisSlotManager:new F.default.Flag,tunnelBinaryNewVersion:new F.default.Flag(!1),encryptedCredentials:new F.default.Flag,computePackagePathFromPackageJsonExports:new F.default.Flag,sendExtensionOnEdgeNonLinux:new F.default.Flag,reuseCliPkgInstallFolder:new F.default.Flag,getPublicIpFrom3rdPartyServices:new F.default.Flag,chromedriverCdnBinariesUrl:new F.default.RoxString(""),sfdcHybridCompany:new F.default.Flag,allowFixingAppIdStructure:new F.default.Flag,enableAppium2BrowserStack:new F.default.Flag,increaseTDCRequestTimeout:new F.default.Flag,accessTokenExpiryMargin:new F.default.RoxNumber(300*1e3),useMV3Extension:new F.default.Flag,testimHeadlessExtensionDownloadUrl:new F.default.RoxString("",[]),applyMobileRestrictionFromDate:new F.default.RoxNumber(17235072e5),removeMobileTrialRestrictions:new F.default.Flag,appiumConnectionRetryCount:new F.default.RoxNumber(0),appiumConnectionRequestTimeout:new F.default.RoxNumber(12e4),DFBrowserVersion:new F.default.RoxString("latest",["latest","latest-1","latest-2"]),DFAcceptInsecureOrigins:new F.default.RoxString("http://jsbin.testim.io"),enableFixForCustomExtensionForLT:new F.default.Flag(!1),enableTestPlanAggregation:new F.default.Flag,secrets:new F.default.Flag,chromeArgsDisableFeatures:new F.default.RoxString(""),useNgrokTunnel:new F.default.Flag(!1),disableCoralogixLogger:new F.default.Flag(!1),disableBetterStackLogger:new F.default.Flag(!1)},F.default.register("default",this.flags)}setProjectId(e){F.default.setCustomStringProperty("projectId",e)}setProjectType(e){F.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){F.default.setCustomStringProperty("productType",e)}setCompanyId(e){F.default.setCustomStringProperty("companyId",e)}setPlanType(e){F.default.setCustomStringProperty("planType",e)}setIsPOC(e){F.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){F.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){F.default.setCustomStringProperty("runnerMode",e)}setRunnerEnvironment(e){F.default.setCustomStringProperty("runnerEnvironment",e)}async fetch({proxy:e}){let t,s,n;if(!uv)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;s=(a,c)=>(0,Om.default)(a,{...c,agent:o}),n=function(a){return new _m.EventSource(a,{fetch:s})}}let i={fetchIntervalInSec:dv,fetchFunction:s,eventSourceImpl:n};return ce(F.default.setup(lm,i),pv).catch(o=>Lm.error("failed to get feature flag status",o))}},O=new jc});function gv(){let r=[];if(!Ue){if(Ni){let{CoralogixTransport:s}=(Sm(),Fe(vm));tr.push(new s({category:"ROOT"}))}r.push(...tr)}let e=async()=>{await Promise.all(tr.map(s=>s.waitForFlush()))},t=s=>tr.forEach(n=>n.setProxy(s));if(om){let s={depth:5,colors:!0};r.push(new yt.transports.Console({format:yt.format.combine(yt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),yt.format.timestamp({format:"HH:mm:ss:SSS"}),yt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Bi.inspect(n.meta,s)}`))}))}return[r,e,t]}function Vc(){return $m}function Wm(r,e){if(Nm||Ue||!r||!e)return;$m={ingestUrl:r.startsWith("https://")?r:`https://${r}`,sourceToken:e};let{BetterStackWinstonTransport:s}=(Pm(),Fe(Am)),n=new s({ingestUrl:r,token:e});tr.push(n),Wc.add(n),Nm=!0,Gc()}function Gc(){let{featureFlagsService:r}=(ue(),Fe(Dm));for(let e of[...tr])(e.name==="Coralogix Transport"&&r.flags.disableCoralogixLogger.isEnabled()||e.name==="BetterStack Transport"&&r.flags.disableBetterStackLogger.isEnabled())&&(Wc.remove(e),tr=tr.filter(s=>s!==e))}function Gm(r){$c=r}function Hm(r){Vm=r}function qm(r){Ue||!r||bv(r)}function Fm(r){return{projectId:Vm,time:new Date().toISOString(),region:qr.getRegion(),...$c&&!r&&{executionId:$c}}}function A(r){return new qr(Wc.child({category:r}))}var Um,yt,Bi,Ui,Bm,mv,fv,tr,Nm,Mm,jm,hv,yv,bv,Tv,wv,Wc,$m,$c,Vm,qr,W=I(()=>{"use strict";Um=R(require("node:os")),yt=R(require("winston"));le();Bi=R(require("node:util"));U();Ui=R(require("chalk")),Bm=R(require("dayjs"));U();mv=Um.hostname(),fv=it(),tr=[],Nm=!1;Mm={depth:5,colors:!0},jm=(r,e,t)=>{let s=`[${(0,Bm.default)().format("HH:mm:ss:SSS")}]`,n=Bi.inspect(e,Mm),i=Bi.inspect(t,Mm);return`${Ui.default.white(s)} ${Ui.default.reset()}SessionPlayer-${Ui.default.red(r)} ${n} ${i}`},[hv,yv,bv]=gv(),Tv=am?"debug":"info",wv={release:!1,branch:"test"},Wc=yt.createLogger({levels:yt.config.syslog.levels,level:Tv,transports:hv,defaultMeta:{name:"runner",hostname:mv,nodeVersion:process.version,runnerVersion:fv,...wv}});$c=null,Vm=null;qr=class r{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}static setRegion(e){r.region=e}static getRegion(){return r.region}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,s={}){let{executionId:n}=s;s.user&&(s.user=Hc(s.user,["email"]));try{this._logger.log(e,{meta:s,message:t,...Fm(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Fm(n)})}catch{}}}waitForFlush(){return yv()}}});var Vi,zr,C,rr,vr,_t,ji,Kr,pe,Zs,ot,sr,Lt,$i,Jr,Wi,en,Q=I(()=>{"use strict";Vi=require("p-retry"),zr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},rr=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},vr=class extends Error{constructor(t,s){super(t instanceof Error?t.message:t,{cause:t});this.type=s}},_t=class extends Vi.AbortError{},ji=class extends Vi.AbortError{},Kr=class extends Vi.AbortError{},pe=class extends Error{},Zs=class extends Error{},ot=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},sr=class extends ot{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Lt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},$i=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Jr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Wi=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},en=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function qc(r){return!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function"&&typeof r.catch=="function"}function ie(r){return(0,Jm.setTimeout)(r)}function zc(r,e){let t=new Promise((s,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([r,t])}function ce(r,e,t="Timeout Error"){_i&&!zm&&(zm=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let s=new pe(t);return e=_i?Number(_i)||6e5:e,Promise.race([r,ie(e).then(()=>{throw s})])}async function oe(r,e,{concurrency:t}={}){if(t){Km||=(await import("p-limit")).default;let s=Km(t);return await Promise.all(Array.from(r,(n,i)=>s(()=>e(n,i))))}return await Promise.all(Array.from(r,e))}function nr(r){return new Promise((e,t)=>{r((s,n)=>s?t(s):e(n))})}var Jm,zm,Km,Kc=I(()=>{"use strict";Jm=require("timers/promises");Q();le();zm=!1});var rn,Xm,Sv,tn,Ym,Ev,Iv,Qm,Zm=I(()=>{"use strict";rn=R(require("lodash"));le();Xm=require("dns");W();Kc();Sv=A("http-request-counters"),tn=!1,Ym=async()=>{if(Ue)return!0;let r=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=!!await oe(r,t=>Xm.promises.lookup(t));return e||(tn=!0),e}catch{return Sv.error("network connectivity test failed"),tn=!0,!1}},Ev=rn.throttle(Ym,10*1e3),Iv=60*1e3*15,Qm=()=>{let r={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},Iv)}function t(n,i=n.name){return async function(...o){e(r.call,i);try{let a=await n.call(null,...o);return e(r.success,i),a}catch(a){throw e(r.fail,i),tn||Ev(),a}}}async function s(){if(tn||!await Ym())return!1;let n=rn.sum([...r.fail.values()]),i=rn.sum([...r.call.values()]);return n<i*.1}return s.counters=r,t.counters=r,t.isNetworkHealthy=s,t.didNetworkConnectivityTestFail=()=>tn,t}});var Xe={};q(Xe,{deleteReq:()=>sn,didNetworkConnectivityTestFail:()=>tl,download:()=>Zc,get:()=>ve,getFullRes:()=>kv,getText:()=>Yc,head:()=>Ov,isNetworkHealthy:()=>el,post:()=>We,postForm:()=>nn,postText:()=>Pv,put:()=>Qc});function xv(){return global.caFileContent}function Cv(r,e){let t=[];r.on("data",s=>{t.push(s)}),r.on("end",()=>{e(null,Buffer.concat(t))})}function Av(){return!("proxy"in bt.default.Request.prototype)&&global.SuperagentProxy&&global.SuperagentProxy(bt.default),global.proxyUri}function Sr(r,e=!1){let t=xv();t&&r.ca(t);let s=!e&&Av();s&&r.proxy(s)}async function ef(r,e,t={},s=Xr,n=0){let i=bt.default.post(r).send(e).timeout(s).set(t);Sr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=r,o.originalRequestTimeout=s,o.additionalSetHeaders=t,o}}async function Xc(r,e,t={},s=Xr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=bt.default.get(r).query(e||{}).timeout(s).set(t);return n&&o.buffer(!0),Sr(o,i),await o}var bt,Jc,at,Xr,Rv,Gt,sn,We,nn,Yc,Pv,ve,kv,Ov,Qc,Zc,el,tl,Ve=I(()=>{"use strict";bt=R(require("superagent"));W();Zm();Jc=A("http-request"),at=Qm(),Xr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,Rv=6e4;Gt=(r,e,t)=>{let s=e.response;e.response instanceof bt.default.Response&&typeof s.toError=="function"&&(e=e.response.toError(),e.requestHeaders=s==null?void 0:s.header,e.responseHeaders=s==null?void 0:s.headers);let n=new Error("").stack;throw Jc.error(r,{...t,error:e,logErrorAndRethrowStack:n}),e};sn=at(async(r,e={},t={},s=Xr)=>{try{let n=bt.default.delete(r).send(e).timeout(s).set(t);Sr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Gt("failed to delete request",n,{url:r})}}),We=at(async({url:r,body:e,headers:t,timeout:s,retry:n})=>{try{let i=await ef(r,e,t,s,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Gt("failed to post request",i,{url:r})}});nn=at(async(r,e,t,s={},n=Xr)=>{let i=bt.default.post(r).type("form").timeout(n).set(s);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),Sr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Gt("failed to post request",o,{url:r})}});Yc=at(async(r,e,t)=>{try{return(await Xc(r,e,t)).text}catch(s){return Gt("failed to getText request",s,{url:r,query:e})}}),Pv=at(async({url:r,body:e,headers:t,timeout:s,retry:n})=>{try{return(await ef(r,e,t,s,n)).text}catch(i){return Gt("failed to post request",i,{url:r})}}),ve=at(async(r,e,t,s,n)=>{try{return(await Xc(r,e,t,s,n)).body}catch(i){return Gt("failed to get request",i,{url:r,query:e})}}),kv=at((r,e,t,s)=>Xc(r,e,t,s)),Ov=at(async r=>{let e=bt.default.head(r).timeout(Xr);Sr(e);try{return await e}catch(t){return Gt("failed to head request",t,{url:r})}}),Qc=at(async(r,e,t={},s=Xr)=>{let n=bt.default.put(r).send(e).timeout(s).set(t);Sr(n);try{return(await n).body}catch(i){return Gt("failed to put request",i,{url:r})}}),Zc=at(async r=>{Jc.info("start to download",{url:r});let e=bt.default.get(r).set("User-Agent","Testim.io").timeout(Rv).buffer(!0).parse(Cv);Sr(e);try{let t=await e;return Jc.info("finished to download",{url:r}),t}catch(t){return Gt("failed to download",t,{url:r})}}),el=at.isNetworkHealthy,tl=at.didNetworkConnectivityTestFail});function Tt(){let r;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?r=Ht.resolve(__dirname,"../../"):r=Ht.resolve(__dirname,""),r):process.cwd()}function Gi(r,e){return De(r)?e||Ht.join(process.cwd(),r.replace(/^.*[\\/]/,"")):e||Ht.basename(r)}function it(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function ol(){try{return tm.node}catch{return""}}async function of(r,e,t=!0){let s=await ct.promises.readdir(r,{withFileTypes:!0});await ct.promises.mkdir(e,{recursive:t});for(let n of s){let i=Ht.join(r,n.name),o=Ht.join(e,n.name);n.isDirectory()?await of(i,o):await ct.promises.copyFile(i,o)}}async function Te(r){try{return await ct.promises.access(r),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Ht,tf,rf,sf,rl,nf,ct,_v,qt,Ye,Hi,sl,Qe,nl,il,al,cl=I(()=>{"use strict";Ht=R(require("node:path")),tf=R(require("node:child_process"));xc();Oi();rf=R(require("unzip-stream")),sf=R(require("p-retry")),rl=R(require("node:fs")),nf=R(require("node:crypto")),ct=require("node:fs"),_v=3;qt=async r=>{let e=await Promise.resolve().then(()=>(Ve(),Xe));return(0,sf.default)(()=>e.download(r),{retries:_v,factor:1})},Ye=async(r,e)=>{let t=await qt(r);return ct.promises.writeFile(e,t.body)};Hi=async(r,e)=>{let t=Gi(r,e);return De(r)?Ye(r,t):ct.promises.copyFile(r,t)},sl=async r=>De(r)?qt(r):ct.promises.readFile(r),Qe=async(r,e)=>(0,ct.createReadStream)(r).pipe(rf.Extract({path:e})),nl=(r,e)=>new Promise((t,s)=>{var o;let n=tf.spawn("tar",["-xzf",r,"-C",e],{stdio:["ignore","pipe","pipe"]}),i="";(o=n.stderr)==null||o.on("data",a=>{i+=a.toString()}),n.on("error",a=>{s(new Error(`Failed to extract tgz file ${r}: ${a.message}. ${i}`))}),n.on("close",a=>{a!==0&&s(new Error(`Failed to extract tgz file ${r}: tar exited with code ${a}. ${i}`)),t()})}),il=r=>(0,ct.statSync)(r).size/1e6;al=async(r,e,t="sha256",s="hex")=>{let n=await rl.promises.readFile(r),i=nf.createHash(t).update(n).digest(s);if(i!==e)throw await rl.promises.unlink(r),new Error(`Checksum mismatch for ${r}. Expected ${e}, got ${i}`)}});var zt={};q(zt,{APPIUM_SESSION_MESSAGE:()=>ml,CLI_MODE:()=>J,MOBILE_APP_SOURCE:()=>qi,MOBILE_RUN_SKIP_REASON:()=>dl,OPERANDS:()=>an,REGION_CONFIG:()=>Qr,SEGMENT_CONFIG:()=>Zr,X_HEADER_RUNNER_ID:()=>fl,gridMessages:()=>wt,gridTypes:()=>N,mobileWeb:()=>ul,runnerStatus:()=>ll,runnerTestStatus:()=>he,socketEventTypes:()=>Dt,stepResult:()=>Yr,test:()=>pl,testRunStatus:()=>on,testStatus:()=>Ze,timeoutMessages:()=>Ae});var Ae,on,ll,he,Ze,wt,ul,pl,Dt,J,N,Yr,qi,dl,ml,fl,Qr,Zr,an,ae=I(()=>{"use strict";Ae={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout",TEST_REACHED_CUSTOM_TIMEOUT_MSG:"test-reached-custom-timeout"},on={COMPLETED:"completed"},ll={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},he={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Ze={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},wt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},ul={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},pl={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Dt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},J={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},N={LOCAL:"local",TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC"},Yr={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error",KEEP_ALIVE_FAILED:"keep-alive-failed"},qi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},dl={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},ml={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"},fl="X-Testim-Runner-ID",Qr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"},Zr={TTL:1e3*60*60*72,CACHE_FN_NAME:"setSegmentConfig"},an=(t=>(t.AND="AND",t.OR="OR",t))(an||{})});function cn(r,e){var t,s,n,i,o,a;return(t=r.browserstack)!=null&&t.browserName||(s=r.saucelabs)!=null&&s.browserName?[(n=r.browser)==null?void 0:n.toLowerCase()]:(i=r.testConfigNames)!=null&&i.length||(o=r.testConfigIds)!=null&&o.length||r.testPlan.length||r.testPlanIds.length||!r.browser?[...new Set(e.map(c=>{var l;return(l=c.runConfig)==null?void 0:l.browserValue}))]:[(a=r.browser)==null?void 0:a.toLowerCase()]}function Lv(){let{argv:r}=process;if(r.includes("--remoteRunId"))return{remoteRunId:r[r.indexOf("--remoteRunId")+1],projectId:r[r.indexOf("--project")+1],token:r[r.indexOf("--token")+1]}}var ln,af,et,Dv,Nv,Mv,Fv,Uv,gl,hl,cf=I(()=>{"use strict";ae();ln=r=>{var e,t;return!!((e=r.testPlan)!=null&&e.length||(t=r.testPlanIds)!=null&&t.length)},af=r=>!!(r.resultId&&r.source==="remote-run"),et=(r,e)=>r.testStatus===Ze.QUARANTINE&&!af(e)&&!e.runQuarantinedTests;Dv=r=>!!r.loginMode,Nv=r=>!!r.tunnelOnlyMode,Mv=r=>!!r.createPrefechedData,Fv=r=>!!r.installLazyDepsMode,Uv=r=>!!r.agentMode,gl=(r,e)=>{r.forEach((t,s)=>{e.has(t)&&(r[s]=`--${t}`)})},hl=r=>{let e=[];return Object.entries(r).forEach(([t,s])=>{s&&e.push(`--${t}`,s)}),e}});function Ki(r=0){return zi.default.duration(r).format("HH:mm:ss.SSS")}function yl(r=0){return zi.default.duration(r).asSeconds()}var zi,lf,Ji,uf=I(()=>{"use strict";zi=R(require("dayjs")),lf=R(require("dayjs/plugin/duration"));zi.default.extend(lf.default);Ji=r=>{let e=Math.floor(r.asMinutes()),t=r.asSeconds()%60||0;return e>0?`${e} min ${Math.floor(t)} sec`:`${Math.floor(t)} sec`}});var un,es,ir,pf,ts,df=I(()=>{"use strict";ae();un=r=>!(!r||"fileName"in r),es=(r,e)=>{if(e===N.TESTIM_TVC)return!1;if(r){if(r.appMetadata&&"iOSSupportedTargetDevice"in r.appMetadata)return r.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in r)return r.fileName.endsWith(".app")}return!1},ir=r=>{var e,t;return((e=r.projectData)==null?void 0:e.type)==="ios"||((t=r.projectData)==null?void 0:t.type)==="android"},pf=r=>r===N.TESTIM_TVC,ts=(r,e)=>pf(e)||!r.flags.allowAppFromDeviceRuns.isEnabled()});function bl(r=4e3){let e=process.memoryUsage(),t=s=>Math.round(s/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>r,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var mf=I(()=>{"use strict"});function gf(r){let e=(0,ff.default)(r);return e.validForNewPackages||e.validForOldPackages}function Tl(r){let e=r.filter(t=>!gf(t.packageName)).map(t=>t.packageName);return e.length>0?e:null}function wl(r){let e=r.filter(t=>t&&(t.includes("../")||t.includes("..\\"))).map(t=>t);return e.length>0?e:null}var ff,vl=I(()=>{"use strict";ff=R(require("validate-npm-package-name"))});var X={};q(X,{OSS:()=>rs,TESTIM_BROWSER_DIR:()=>vt,buildBasicHeader:()=>Rc,calcPercentile:()=>Qi,copyDir:()=>of,delay:()=>ie,doesPathExist:()=>Te,download:()=>qt,downloadAndSave:()=>Ye,extractElementId:()=>Be,extractTgz:()=>nl,formatTimeoutDuration:()=>Ji,getArgsOnRemoteRunFailure:()=>Lv,getBrowserInfo:()=>jv,getCdpAddressForHost:()=>Rr,getCliLocation:()=>Tt,getDuration:()=>Ki,getDurationSec:()=>yl,getEnginesVersion:()=>ol,getEnvironmentGitBranch:()=>Ir,getInvalidPackageNames:()=>Tl,getInvalidPackagePaths:()=>wl,getLinksFromUnescapeHTML:()=>mn,getLocalFileSizeInMB:()=>il,getMemorySnapshot:()=>bl,getPlanType:()=>Yi,getRunConfigByBrowserName:()=>pn,getRunnerVersion:()=>it,getSource:()=>Hi,getSourceAsBuffer:()=>sl,getSourcePath:()=>Gi,getTestUrl:()=>Ke,getUniqBrowsers:()=>cn,groupTestsByRetries:()=>El,guid:()=>ne,hasTestPlanFlag:()=>ln,isAgentMode:()=>Uv,isAppFromDevice:()=>un,isAppFromDeviceDisabled:()=>ts,isCreatePrefetchedDataMode:()=>Mv,isInstallLazyDepsMode:()=>Fv,isLoginMode:()=>Dv,isMobileProject:()=>ir,isPromise:()=>qc,isQuarantineAndNotRemoteRun:()=>et,isRemoteRun:()=>af,isTestimVirtualGrid:()=>pf,isTunnelOnlyMode:()=>Nv,isURL:()=>De,isValidPackageName:()=>gf,maskObjectFields:()=>Hc,maskSecret:()=>vf,promiseAbort:()=>zc,promiseFromCallback:()=>nr,promiseMap:()=>oe,promiseTimeout:()=>ce,removePropertyFromObject:()=>Xi,replaceArgsWithNoDashes:()=>gl,sanitizeNumberValue:()=>Er,shouldBlockVirtualIosBuild:()=>es,spreadObjectToArgs:()=>hl,unescapeHTML:()=>dn,unzipFile:()=>Qe,verifyChecksum:()=>al});function Er(r,e){let t=Number(r);return Number.isNaN(t)||t<=0?e:t}function jv(r){return r=r.toLowerCase(),Sl.find(e=>e.browserValue===r)}function pn(r,e,t){r=r==null?void 0:r.toLowerCase();let s=Sl.find(i=>i.browserName.toLowerCase()===r||r.includes(i.synonyms))||Sl[0],n=rs.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=rs.find(i=>i.sl.platform===e.platform):e.platformName&&(n=rs.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=rs.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=rs.find(i=>i.bs.platform===t.platform))),ss.merge(s,n)}function Ir(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH||process.env.GITHUB_BRANCH_NAME}function Xi(r,e,t){for(let s in r)Object.hasOwn(r,s)&&(t(s,e)?delete r[s]:typeof r[s]=="object"&&Xi(r[s],e,t))}function Be(r){return r.ELEMENT||r[Zt]}function Yi(r){r||={};let e=Date.now(),t=r.expireAt||r.expireAT;return r.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function El(r=[]){return ss.chain(r).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let s=[...t].sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=ss.cloneDeep(s.at(-1));return n&&(n.retryTestResults=s,e.push(n)),e},[]).compact().value()}function dn(r){return wf.parseFromString(`<html><body>${r}</body></html>`,"text/html").documentElement.textContent}function mn(r){return[...wf.parseFromString(`<html><body>${r}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function Rr(r,e){let t=await Promise.resolve().then(()=>(Ve(),Xe));try{return(await t.get(`http://${r}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}function vf(r,{visiblePrefixLength:e=1,visibleSuffixLength:t=0,maskCharacter:s="*"}={}){if(!(r!=null&&r.length))return"";if(r.length-(e+t)<r.length*.8)return"".padEnd(r.length,s);let o=r.slice(0,e),a=r.slice(r.length-t);return`${o}${s.repeat(Math.ceil(r.length*.9))}${a}`}function Hc(r,e){let t=new Set(e),s=n=>{if(!(n===null||typeof n!="object")){if(Array.isArray(n)){n.forEach(i=>s(i));return}for(let i of Object.keys(n))if(t.has(i)){let o=n[i];o!=null&&(n[i]=vf(String(o)))}else typeof n[i]=="object"&&s(n[i])}};return s(r),r}var yf,ss,bf,Tf,Bv,vt,hf,rs,Sl,Qi,wf,U=I(()=>{"use strict";yf=R(require("os")),ss=R(require("lodash")),bf=R(require("path")),Tf=require("linkedom");Hr();cl();cf();uf();xc();Kc();df();mf();vl();Bv=yf.homedir(),vt=bf.join(Bv,".testim-browser-profile"),hf="133",rs=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"MacOS Tahoe",bs:{os:"OS X",os_version:"Tahoe",safari_version:"26.2"},sl:{},lt:{platform:"MacOS Tahoe"}},{osName:"MacOS Sequoia",bs:{os:"OS X",os_version:"Sequoia",safari_version:"18.4"},sl:{platform:"macOS 15",safari_version:"latest"},lt:{platform:"MacOS Sequoia"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17.3"},sl:{platform:"macOS 14",safari_version:"latest"},lt:{platform:"macOS Sonoma"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"},lt:{platform:"macOS Big Sur"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{},lt:{platform:"macOS Catalina"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{},lt:{platform:"macOS Mojave"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{},lt:{platform:"macOS High Sierra"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{},lt:{platform:"macOS Sierra"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{},lt:{platform:"OS X El Capitan"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{},lt:{platform:"OS X Yosemite"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{},lt:{platform:"OS X Mountain Lion"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Sl=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:hf},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:hf},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Qi=(r,e)=>{if(r.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(r=[...r].sort((s,n)=>s-n),e<=0)return r[0];if(e>=100)return r.at(-1);let t=Math.ceil(r.length*(e/100))-1;return r[t]};wf=new Tf.DOMParser});var Il={};q(Il,{$schema:()=>$v,default:()=>qv,definitions:()=>Wv,properties:()=>Hv,required:()=>Gv,type:()=>Vv});var $v,Wv,Vv,Gv,Hv,qv,Sf=I(()=>{$v="http://json-schema.org/draft-07/schema#",Wv={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},Vv="object",Gv=["entries"],Hv={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},qv={$schema:$v,definitions:Wv,type:Vv,required:Gv,properties:Hv}});async function Pf(){try{return await ce(Zi.promises.readFile(so()).then(async r=>{let e=await Af;return Jv(e,r)}),3e4)}catch{return{}}}function Jv(r,e){let t=e.slice(0,16),s=e.slice(16),n=Buffer.from(r),i=is.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(s);return JSON.parse(Buffer.concat([o,i.final()]))}function lt(r,e,t=zv,s=void 0){return async()=>{if(!Rf)return await r();let n=e;s&&(e+=JSON.stringify(s));let i=await os(e);if(i)return fn.debug("cache hit:",{fnName:e}),i;if(fn.debug("cache miss:",{fnName:e}),!xf)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await r();return o&&await Xv(e,o,t),o}}async function os(r){let t=(await no)[r];if(!t)return;let{value:s,expiry:n}=t;if(!(n<Date.now())&&s)return s}async function Xv(r,e,t){if(Rl)throw fn.error("calling set after waitForSave is not allowed",{key:r,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let s=await no;s[r]={value:e,expiry:Date.now()+t},Cf=new Promise(n=>{ro=n}),Kv(s)}catch{fn.error("failed updating cache")}}async function as(){let r=await no;Object.keys(r).forEach(e=>{delete r[e]})}function kf(r){Rf=r}function Yv(r=!0){xf=r}async function Of(){try{return Rl=!0,await Cf}finally{Rl=!1}}function _f(r){to=r,no=Pf()}var Zi,eo,is,Ef,fn,to,If,ro,Rf,xf,Rl,Cf,Af,zv,so,no,Kv,Lf,Df,$C,Nf,Kt=I(()=>{"use strict";Zi=R(require("fs")),eo=R(require("path")),is=R(require("crypto"));U();Ef=require("lodash");W();fn=A("local cache"),to=eo.resolve(Tt(),"testim-cache"),Rf=!0,xf=!0,Rl=!1,Cf=new Promise(r=>{ro=r}),Af=new Promise(r=>{If=r}),zv=1e3*60*60*3,so=()=>eo.resolve(eo.resolve(to,"testim.cache"));no=Pf(),Kv=(0,Ef.debounce)(async r=>{let e;try{let t=await Af,s=is.randomBytes(16),n=JSON.stringify(r),i=Buffer.from(t),o=is.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),s),a=Buffer.concat([s,o.update(n),o.final()]);await Te(to)||await Zi.promises.mkdir(to,{recursive:!0}),await Zi.promises.writeFile(so(),a)}catch(t){fn.error("failed saving cache",{err:t}),e=t}ro(e?{success:!1,error:e}:{success:!0})},200);Lf=If,Df=kf.bind(void 0,!1),$C=kf.bind(void 0,!0),Nf=()=>Yv(!1)});function io(){return{cliLocation:Tt(),userInfo:cs.userInfo(),platform:cs.platform(),release:cs.release()}}var cs,xl=I(()=>{"use strict";cs=R(require("node:os"));U()});function Qv(r){try{return oo.resolve(oo.dirname(require.resolve(`${r}/package.json`)),require(`${r}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(r);throw e}}function ar(r){let e=Qv(r);return require(e)}var oo,gn=I(()=>{"use strict";oo=R(require("path"))});function Zv(r){let t=/EACCES[^']+'(.+)'/.exec(r);return t===null?!1:t[1]}function eS(r){return/The "to" argument must be of type string./.exec(r)}function Bf(r,e,t){let s=Zv(r),n=eS(r);return s||n?(Uf.info("Failed to install package due to insufficient write access",{...io(),package:t,path:s}),console.error(`
|
|
2
|
+
"use strict";var jw=Object.create;var Sn=Object.defineProperty;var $w=Object.getOwnPropertyDescriptor;var Ww=Object.getOwnPropertyNames;var Vw=Object.getPrototypeOf,Gw=Object.prototype.hasOwnProperty;var I=(s,e)=>()=>(s&&(e=s(s=0)),e);var q=(s,e)=>{for(var t in e)Sn(s,t,{get:e[t],enumerable:!0})},Hd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ww(e))!Gw.call(s,i)&&i!==t&&Sn(s,i,{get:()=>e[i],enumerable:!(r=$w(e,i))||r.enumerable});return s};var R=(s,e,t)=>(t=s!=null?jw(Vw(s)):{},Hd(e||!s||!s.__esModule?Sn(t,"default",{value:s,enumerable:!0}):t,s)),Me=s=>Hd(Sn({},"__esModule",{value:!0}),s);var Be={};q(Be,{log:()=>M,measure:()=>qw});function M(...s){if(!zd)return;let e=Date.now();console.log(`${e-Hw} ${e-qd} `,...s),qd=e}function qw(s,e){if(!zd)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var zd,Hw,qd,je=I(()=>{"use strict";zd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,Hw=Date.now(),qd=Date.now()});var Qt,Gr=I(()=>{"use strict";Qt="element-6066-11e4-a52e-4f735466cecf"});function ce(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let i=Math.floor(Math.random()*e.length);t+=e[i]}return t}function ze(s,e,t,r,i){let n="";return i=i?encodeURIComponent(i):"master",e&&t&&(n=`${s}/#/project/${e}/branch/${i}/test/${t}`,r&&(n+=`?result-id=${r}`)),n}function Ic(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function De(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var Rc=I(()=>{"use strict"});var Cc,Kd,Jd,kn=I(()=>{Cc={"v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"2.1.1"},Kd={"@applitools/eyes-sdk-core":"13.11.34-legacy.1","@testim/shared-logger":"workspace:*","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"2.1.3","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.4",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.8.1",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6","form-data":"^4.0.4",express:"4.22.1",fkill:"7.2.1","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jsonwebtoken:"9.0.3",linkedom:"0.18.0",lodash:"4.17.23","memory-fs":"0.5.0",ms:"2.1.2","node-fetch":"2.7.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"5.4.12",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.8.0","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"7.0.0","ua-parser-js":"0.7.39","unzip-stream":"0.3.4",uuid:"11.0.5","validate-npm-package-name":"3.0.0",webdriverio:"9.18.4",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},Jd={node:">= 18.0.0"}});var br,Tr,Xd,qs,Jw,Zt,Yd,Qd,On,st,Zd,be,em,tm,_n,Fe,Ac,rm,Ln,sm,Dn,Pc,kc,im,nm,Ux,Bx,om,am,cm,lm,Oc,um,_c,pm,zs,Ks,le=I(()=>{"use strict";br=process.env.SERVICES_HOST||"https://services.testim.io",Tr="https://app.testim.io";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:br,br=process.env.SERVICES_HOST);Xd=process.env.TESTIM_REGION||"us-west-2",qs=process.env.RUNNER_ENVIRONMENT||"production",Jw={production:"",staging:".staging",development:".dev"},Zt=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${Jw[qs]||""}.testim.io`,Yd=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Qd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),On=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),st=process.env.EDITOR_URL,Zd=process.env.WEBSOCKET_HOST||`${br}/ws`,be=()=>br,em=parseInt(process.env.LOGGER_CONSOLE||"0",10),tm=parseInt(process.env.LOGGER_DEBUG||"0",10),_n=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),Fe=parseInt(process.env.IS_ON_PREM||"0",10),Ac=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,rm=parseInt(process.env.DEBUG_MODE||"0",10),Ln=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,sm=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",Dn=process.env.CORALOGIX_PRIVATE_KEY||"cxtp_cLWBXCtKOy35gMEA27eFjtY4dqrLo6",Pc=process.env.BETTERSTACK_INGEST_URL_US||"https://s1764893.us-east-9.betterstackdata.com",kc=process.env.BETTERSTACK_TOKEN_US||"hZwS8Qt91YwDSDSK6CGicabR",im=process.env.BETTERSTACK_INGEST_URL_EU||"",nm=process.env.BETTERSTACK_TOKEN_EU||"",Ux=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),Bx=process.env.APPIUM_VERSION||"1.10.1",om=process.env.GATEWAY_URL,am=()=>process.env.EXTENSION_SERVICES_HOST||br,cm=300*1e3,lm=40,Oc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",um=process.env.TDC_DEVICES_API_PATH||"v0",_c=process.env.TDC_APPS_API_PATH||"v1",pm=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",zs=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Ks=s=>{br=s,process.env.SERVICES_HOST=s,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:br}});var dm,Nn,mm=I(()=>{"use strict";dm=R(require("superagent"));le();Nn=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=Dn,this.applicationName=e.applicationName,this.subsystemName=e.subsystemName,this.flushIntervalMs=e.flushIntervalMs||2e3,this.maxBufferedLogsCount=e.maxBufferedLogsCount||50,this.interval=setInterval(()=>this.flushLogs(),this.flushIntervalMs)}addLog(e){this.logs.push(e),this.logs.length>=this.maxBufferedLogsCount&&this.flushLogs()}setProxy(e){this.proxy=e}async waitForFlush(){clearInterval(this.interval),await this.flushLogs()}async flushLogs(){try{if(this.logs.length===0)return;let e={applicationName:this.applicationName,subsystemName:this.subsystemName,logEntries:[...this.logs]};this.logs=[];let t=dm.default.post(this.url).set("Content-Type","application/json; charset=UTF-8").set("Authorization",`Bearer ${this.token}`).send(e);this.proxy&&t.proxy(this.proxy),await t}catch{}}}});var gm={};q(gm,{CoralogixTransport:()=>Lc});var fm,Xw,Yw,Lc,hm=I(()=>{"use strict";fm=R(require("winston-transport"));mm();Xw={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},Yw=["err","error","reason","e"],Lc=class extends fm.default{constructor(e){super(e),this.name="Coralogix Transport",this.category=e.category,this.logger=new Nn({applicationName:"testim",subsystemName:"runner"})}log(e,t){let{category:r,level:i,message:n,meta:o={},...a}=e,c={...o,...a},l={severity:Xw[i],text:n,category:r||this.category};c.className&&(l.className=c.className),c.methodName&&(l.methodName=c.methodName),c.threadId&&(l.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let d=!1;o instanceof Error&&(d=!0,c.msg=o.message+o.stack,n&&(c.msg=`${n}
|
|
3
|
+
${c.msg}`));for(let m of Yw)o[m]instanceof Error&&(c[m]={message:o[m].message,stack:o[m].stack,name:o[m].name,type:o[m].type,cause:o[m].cause,...o[m]});Object.keys(c).length>0&&(n&&!d&&(c.msg=n),l.text=JSON.stringify(c)),this.logger.addLog(l),t(null,!0)}setProxy(e){this.logger.setProxy(e)}async waitForFlush(){return await this.logger.waitForFlush()}}});var Ke,ym,bm=I(()=>{"use strict";Ke={debug:1,verbose:2,info:3,warn:4,error:5,fatal:6},ym={1:"debug",2:"verbose",3:"info",4:"warn",5:"error",6:"fatal"}});function Dc(){return typeof global<"u"&&{}.toString.call(global)==="[object global]"}function Nc(s,e){return async t=>{await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}}function Mc(s,e,t){let r=require("superagent");return async i=>{let n=r.post(s).set("Content-Type","application/json").set("Authorization",`Bearer ${e}`).send(i),o=t==null?void 0:t();o&&n.proxy(o),await n}}var Fc=I(()=>{"use strict"});var Js,Tm=I(()=>{"use strict";Fc();Js=class{constructor(e){this.buffer=[];e.sendLogs?this.sendLogs=e.sendLogs:Dc()?this.sendLogs=Mc(e.ingestUrl,e.token,e.getProxy):this.sendLogs=Nc(e.ingestUrl,e.token),this.maxBufferSize=e.maxBufferSize??50,this.flushIntervalMs=e.flushIntervalMs??2e3,this.flushInterval=setInterval(()=>this.flush(),this.flushIntervalMs)}addLog(e){this.buffer.push(e),this.buffer.length>=this.maxBufferSize&&this.flush()}async flush(){if(this.buffer.length===0)return;let e=[...this.buffer];this.buffer=[];try{await this.sendLogs(e)}catch{}}async waitForFlush(){clearInterval(this.flushInterval),await this.flush()}destroy(){clearInterval(this.flushInterval)}}});var wm=I(()=>{"use strict";bm();Tm();Fc()});var Sm={};q(Sm,{BetterStackWinstonTransport:()=>Uc});var vm,Qw,Zw,Uc,Em=I(()=>{"use strict";vm=R(require("winston-transport"));wm();Qw={debug:Ke.debug,silly:Ke.verbose,verbose:Ke.verbose,silent:Ke.verbose,info:Ke.info,http:Ke.info,warn:Ke.warn,warning:Ke.warn,error:Ke.error,critical:Ke.fatal,crit:Ke.fatal},Zw=["err","error","reason","e"],Uc=class extends vm.default{constructor(e){super(e),this.name="BetterStack Transport",this.logger=new Js({ingestUrl:e.ingestUrl,token:e.token,getProxy:()=>this.proxy})}log(e,t){let{category:r,level:i,message:n,meta:o={},...a}=e,c={...o,...a},l=Qw[i]??Ke.info,d={dt:new Date().toISOString(),level:ym[l],severity:l,message:n,category:r||"ROOT",applicationName:"testim",subsystemName:"runner"};c.className&&(d.className=c.className),c.methodName&&(d.methodName=c.methodName),c.threadId&&(d.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let m=!1;o instanceof Error&&(m=!0,c.msg=o.message+o.stack,n&&(c.msg=`${n}
|
|
4
|
+
${c.msg}`));for(let p of Zw)o[p]instanceof Error&&(c[p]={message:o[p].message,stack:o[p].stack,name:o[p].name,type:o[p].type,cause:o[p].cause,...o[p]});Object.keys(c).length>0&&(n&&!m&&(c.msg=n),Object.assign(d,c)),this.logger.addLog(d),t(null,!0)}setProxy(e){this.proxy=e}async waitForFlush(){return await this.logger.waitForFlush()}}});var Am={};q(Am,{featureFlagsService:()=>O});var F,Rm,xm,Cm,ev,tv,rv,Im,Mn,Bc,O,pe=I(()=>{"use strict";F=R(require("rox-node")),Rm=R(require("node-fetch")),xm=require("eventsource");W();U();le();Cm=A("FeatureFlagsService"),ev=!Fe&&!0&&!om,tv=2e4,rv=3600*24,Im=["labs","disabled","enabled"],Mn=class extends F.default.RoxString{constructor(e="disabled"){super(e,Im)}getValue(){let e=super.getValue();return Im.includes(e)?e:(Cm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Bc=class{constructor(){this.flags={useNewWSCLI:new F.default.Flag,useSafariWebdriverVisibilityChecks:new F.default.Flag,useClickimVisibilityChecks:new F.default.Flag,runGetElementCodeInAut:new F.default.Flag,enableFrameSwitchOptimization:new F.default.Flag,maximumJsResultSize:new F.default.RoxNumber(2e3*1024),skipFileInputClicks:new F.default.Flag,errorMessageOnBadNetwork:new F.default.Flag(!0),warnOnBadNetwork:new F.default.Flag(!1),overrideAzureStorageUrl:new F.default.Flag,autoSaveDownloadFileFireFox:new F.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new F.default.Flag(!0),experimentalPreCodeCompilation:new F.default.Flag(!0),experimentalAsyncCustomCode:new F.default.Flag,useSameBrowserForMultiTests:new Mn("labs"),highSpeedMode:new Mn,usePortedHtml5DragDrop:new F.default.Flag,testNamesToBeforeSuiteHook:new F.default.Flag,addCustomCapabilities:new F.default.RoxString("{}"),addCustomLTtunnelNTLMOptions:new F.default.RoxString("{}"),LTNetworkCapabilities:new F.default.Flag,downloadToBase64:new F.default.Flag,publicGridURL:new F.default.RoxString("public-grid.testim.io"),allowAppFromDeviceRuns:new F.default.Flag(!0),unsupportedCapsFields:new F.default.RoxString("[]"),dontFocusOnInit:new F.default.Flag,retryOnSeleniumHubError:new F.default.Flag,enableLambdaTestTunnelNTLM:new F.default.Flag,enableLambdaTestTunnelSkipUpgrade:new F.default.Flag,tdcHsPreventNetworkCapture:new F.default.Flag,enableBatchTDC:new F.default.Flag,clearRunnerFileCache:new F.default.Flag,forceTurboModeIfNeeded:new F.default.Flag,redisSlotManager:new F.default.Flag,tunnelBinaryNewVersion:new F.default.Flag(!1),encryptedCredentials:new F.default.Flag,computePackagePathFromPackageJsonExports:new F.default.Flag,sendExtensionOnEdgeNonLinux:new F.default.Flag,reuseCliPkgInstallFolder:new F.default.Flag,getPublicIpFrom3rdPartyServices:new F.default.Flag,chromedriverCdnBinariesUrl:new F.default.RoxString(""),sfdcHybridCompany:new F.default.Flag,allowFixingAppIdStructure:new F.default.Flag,enableAppium2BrowserStack:new F.default.Flag,increaseTDCRequestTimeout:new F.default.Flag,accessTokenExpiryMargin:new F.default.RoxNumber(300*1e3),useMV3Extension:new F.default.Flag,testimHeadlessExtensionDownloadUrl:new F.default.RoxString("",[]),applyMobileRestrictionFromDate:new F.default.RoxNumber(17235072e5),removeMobileTrialRestrictions:new F.default.Flag,appiumConnectionRetryCount:new F.default.RoxNumber(0),appiumConnectionRequestTimeout:new F.default.RoxNumber(12e4),DFBrowserVersion:new F.default.RoxString("latest",["latest","latest-1","latest-2"]),DFAcceptInsecureOrigins:new F.default.RoxString("http://jsbin.testim.io"),enableFixForCustomExtensionForLT:new F.default.Flag(!1),enableTestPlanAggregation:new F.default.Flag,secrets:new F.default.Flag,chromeArgsDisableFeatures:new F.default.RoxString(""),useNgrokTunnel:new F.default.Flag(!1),disableCoralogixLogger:new F.default.Flag(!1),disableBetterStackLogger:new F.default.Flag(!1)},F.default.register("default",this.flags)}setProjectId(e){F.default.setCustomStringProperty("projectId",e)}setProjectType(e){F.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){F.default.setCustomStringProperty("productType",e)}setCompanyId(e){F.default.setCustomStringProperty("companyId",e)}setPlanType(e){F.default.setCustomStringProperty("planType",e)}setIsPOC(e){F.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){F.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){F.default.setCustomStringProperty("runnerMode",e)}setRunnerEnvironment(e){F.default.setCustomStringProperty("runnerEnvironment",e)}async fetch({proxy:e}){let t,r,i;if(!ev)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,c)=>(0,Rm.default)(a,{...c,agent:o}),i=function(a){return new xm.EventSource(a,{fetch:r})}}let n={fetchIntervalInSec:rv,fetchFunction:r,eventSourceImpl:i};return ae(F.default.setup(sm,n),tv).catch(o=>Cm.error("failed to get feature flag status",o))}},O=new Bc});function nv(){let s=[];if(!Fe){if(Dn){let{CoralogixTransport:r}=(hm(),Me(gm));er.push(new r({category:"ROOT"}))}s.push(...er)}let e=async()=>{await Promise.all(er.map(r=>r.waitForFlush()))},t=r=>er.forEach(i=>i.setProxy(r));if(em){let r={depth:5,colors:!0};s.push(new gt.transports.Console({format:gt.format.combine(gt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),gt.format.timestamp({format:"HH:mm:ss:SSS"}),gt.format.printf(i=>`[${i.timestamp}] ${i.level} ${i.category}: ${i.message} ${Un.inspect(i.meta,r)}`))}))}return[s,e,t]}function Wc(){return Nm}function Mm(s,e){if(Pm||Fe||!s||!e)return;Nm={ingestUrl:s.startsWith("https://")?s:`https://${s}`,sourceToken:e};let{BetterStackWinstonTransport:r}=(Em(),Me(Sm)),i=new r({ingestUrl:s,token:e});er.push(i),$c.add(i),Pm=!0,Vc()}function Vc(){let{featureFlagsService:s}=(pe(),Me(Am));for(let e of[...er])(e.name==="Coralogix Transport"&&s.flags.disableCoralogixLogger.isEnabled()||e.name==="BetterStack Transport"&&s.flags.disableBetterStackLogger.isEnabled())&&($c.remove(e),er=er.filter(r=>r!==e))}function Um(s){jc=s}function Bm(s){Fm=s}function jm(s){Fe||!s||cv(s)}function Om(s){return{projectId:Fm,time:new Date().toISOString(),region:Hr.getRegion(),...jc&&!s&&{executionId:jc}}}function A(s){return new Hr($c.child({category:s}))}var _m,gt,Un,Fn,Lm,sv,iv,er,Pm,km,Dm,ov,av,cv,lv,uv,$c,Nm,jc,Fm,Hr,W=I(()=>{"use strict";_m=R(require("node:os")),gt=R(require("winston"));le();Un=R(require("node:util"));U();Fn=R(require("chalk")),Lm=R(require("dayjs"));U();sv=_m.hostname(),iv=it(),er=[],Pm=!1;km={depth:5,colors:!0},Dm=(s,e,t)=>{let r=`[${(0,Lm.default)().format("HH:mm:ss:SSS")}]`,i=Un.inspect(e,km),n=Un.inspect(t,km);return`${Fn.default.white(r)} ${Fn.default.reset()}SessionPlayer-${Fn.default.red(s)} ${i} ${n}`},[ov,av,cv]=nv(),lv=tm?"debug":"info",uv={release:!1,branch:"test"},$c=gt.createLogger({levels:gt.config.syslog.levels,level:lv,transports:ov,defaultMeta:{name:"runner",hostname:sv,nodeVersion:process.version,runnerVersion:iv,...uv}});jc=null,Fm=null;Hr=class s{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}static setRegion(e){s.region=e}static getRegion(){return s.region}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:i}=r;r.user&&(r.user=Gc(r.user,["email"]));try{this._logger.log(e,{meta:r,message:t,...Om(i)})}catch(n){try{this._logger.log("crit",{message:`failed to log message ${n.message}, ${n.stack}`,...Om(i)})}catch{}}}waitForFlush(){return av()}}});var Wn,qr,C,tr,wr,Ot,Bn,zr,ue,Xs,nt,rr,_t,jn,Kr,$n,Ys,Q=I(()=>{"use strict";Wn=require("p-retry"),qr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},tr=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},wr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},Ot=class extends Wn.AbortError{},Bn=class extends Wn.AbortError{},zr=class extends Wn.AbortError{},ue=class extends Error{},Xs=class extends Error{},nt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},rr=class extends nt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},_t=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},jn=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Kr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},$n=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Ys=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Hc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ie(s){return(0,Vm.setTimeout)(s)}function qc(s,e){let t=new Promise((r,i)=>{e.onabort=()=>{i(e.reason)}});return Promise.race([s,t])}function ae(s,e,t="Timeout Error"){On&&!$m&&($m=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ue(t);return e=On?Number(On)||6e5:e,Promise.race([s,ie(e).then(()=>{throw r})])}async function ne(s,e,{concurrency:t}={}){if(t){Wm||=(await import("p-limit")).default;let r=Wm(t);return await Promise.all(Array.from(s,(i,n)=>r(()=>e(i,n))))}return await Promise.all(Array.from(s,e))}function sr(s){return new Promise((e,t)=>{s((r,i)=>r?t(r):e(i))})}var Vm,$m,Wm,zc=I(()=>{"use strict";Vm=require("timers/promises");Q();le();$m=!1});var Zs,Gm,dv,Qs,Hm,mv,fv,qm,zm=I(()=>{"use strict";Zs=R(require("lodash"));le();Gm=require("dns");W();zc();dv=A("http-request-counters"),Qs=!1,Hm=async()=>{if(Fe)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=!!await ne(s,t=>Gm.promises.lookup(t));return e||(Qs=!0),e}catch{return dv.error("network connectivity test failed"),Qs=!0,!1}},mv=Zs.throttle(Hm,10*1e3),fv=60*1e3*15,qm=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(i,n){let o=i.get(n)||0;i.set(n,o+1),setTimeout(()=>{let a=i.get(n)||1;i.set(n,a-1)},fv)}function t(i,n=i.name){return async function(...o){e(s.call,n);try{let a=await i.call(null,...o);return e(s.success,n),a}catch(a){throw e(s.fail,n),Qs||mv(),a}}}async function r(){if(Qs||!await Hm())return!1;let i=Zs.sum([...s.fail.values()]),n=Zs.sum([...s.call.values()]);return i<n*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Qs,t}});var Je={};q(Je,{deleteReq:()=>ei,didNetworkConnectivityTestFail:()=>el,download:()=>Qc,get:()=>ve,getFullRes:()=>wv,getText:()=>Xc,head:()=>vv,isNetworkHealthy:()=>Zc,post:()=>$e,postForm:()=>ti,postText:()=>Tv,put:()=>Yc});function hv(){return global.caFileContent}function yv(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function bv(){return!("proxy"in ht.default.Request.prototype)&&global.SuperagentProxy&&global.SuperagentProxy(ht.default),global.proxyUri}function vr(s,e=!1){let t=hv();t&&s.ca(t);let r=!e&&bv();r&&s.proxy(r)}async function Km(s,e,t={},r=Jr,i=0){let n=ht.default.post(s).send(e).timeout(r).set(t);vr(n),i&&n.retry(i);try{return await n}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Jc(s,e,t={},r=Jr,{isBinary:i=!1,skipProxy:n=!1}={}){let o=ht.default.get(s).query(e||{}).timeout(r).set(t);return i&&o.buffer(!0),vr(o,n),await o}var ht,Kc,ot,Jr,gv,Vt,ei,$e,ti,Xc,Tv,ve,wv,vv,Yc,Qc,Zc,el,We=I(()=>{"use strict";ht=R(require("superagent"));W();zm();Kc=A("http-request"),ot=qm(),Jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,gv=6e4;Vt=(s,e,t)=>{let r=e.response;e.response instanceof ht.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let i=new Error("").stack;throw Kc.error(s,{...t,error:e,logErrorAndRethrowStack:i}),e};ei=ot(async(s,e={},t={},r=Jr)=>{try{let i=ht.default.delete(s).send(e).timeout(r).set(t);vr(i);let n=await i;return n.type==="text/plain"?n.text:n.body}catch(i){return Vt("failed to delete request",i,{url:s})}}),$e=ot(async({url:s,body:e,headers:t,timeout:r,retry:i})=>{try{let n=await Km(s,e,t,r,i);return n.type==="text/plain"?n.text:n.body}catch(n){return Vt("failed to post request",n,{url:s})}});ti=ot(async(s,e,t,r={},i=Jr)=>{let n=ht.default.post(s).type("form").timeout(i).set(r);n.field(e),Object.entries(t).forEach(([o,a])=>{n.attach(o,a.buffer,a.fileName)}),vr(n);try{let o=await n;return o.type==="text/plain"?o.text:o.body}catch(o){return Vt("failed to post request",o,{url:s})}});Xc=ot(async(s,e,t)=>{try{return(await Jc(s,e,t)).text}catch(r){return Vt("failed to getText request",r,{url:s,query:e})}}),Tv=ot(async({url:s,body:e,headers:t,timeout:r,retry:i})=>{try{return(await Km(s,e,t,r,i)).text}catch(n){return Vt("failed to post request",n,{url:s})}}),ve=ot(async(s,e,t,r,i)=>{try{return(await Jc(s,e,t,r,i)).body}catch(n){return Vt("failed to get request",n,{url:s,query:e})}}),wv=ot((s,e,t,r)=>Jc(s,e,t,r)),vv=ot(async s=>{let e=ht.default.head(s).timeout(Jr);vr(e);try{return await e}catch(t){return Vt("failed to head request",t,{url:s})}}),Yc=ot(async(s,e,t={},r=Jr)=>{let i=ht.default.put(s).send(e).timeout(r).set(t);vr(i);try{return(await i).body}catch(n){return Vt("failed to put request",n,{url:s})}}),Qc=ot(async s=>{Kc.info("start to download",{url:s});let e=ht.default.get(s).set("User-Agent","Testim.io").timeout(gv).buffer(!0).parse(yv);vr(e);try{let t=await e;return Kc.info("finished to download",{url:s}),t}catch(t){return Vt("failed to download",t,{url:s})}}),Zc=ot.isNetworkHealthy,el=ot.didNetworkConnectivityTestFail});function yt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Gt.resolve(__dirname,"../../"):s=Gt.resolve(__dirname,""),s):process.cwd()}function Vn(s,e){return De(s)?e||Gt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Gt.basename(s)}function it(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function nl(){try{return Jd.node}catch{return""}}async function Zm(s,e,t=!0){let r=await at.promises.readdir(s,{withFileTypes:!0});await at.promises.mkdir(e,{recursive:t});for(let i of r){let n=Gt.join(s,i.name),o=Gt.join(e,i.name);i.isDirectory()?await Zm(n,o):await at.promises.copyFile(n,o)}}async function Te(s){try{return await at.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Gt,Jm,Xm,Ym,tl,Qm,at,Sv,Ht,Xe,Gn,rl,Ye,sl,il,ol,al=I(()=>{"use strict";Gt=R(require("node:path")),Jm=R(require("node:child_process"));Rc();kn();Xm=R(require("unzip-stream")),Ym=R(require("p-retry")),tl=R(require("node:fs")),Qm=R(require("node:crypto")),at=require("node:fs"),Sv=3;Ht=async s=>{let e=await Promise.resolve().then(()=>(We(),Je));return(0,Ym.default)(()=>e.download(s),{retries:Sv,factor:1})},Xe=async(s,e)=>{let t=await Ht(s);return at.promises.writeFile(e,t.body)};Gn=async(s,e)=>{let t=Vn(s,e);return De(s)?Xe(s,t):at.promises.copyFile(s,t)},rl=async s=>De(s)?Ht(s):at.promises.readFile(s),Ye=async(s,e)=>(0,at.createReadStream)(s).pipe(Xm.Extract({path:e})),sl=(s,e)=>new Promise((t,r)=>{var o;let i=Jm.spawn("tar",["-xzf",s,"-C",e],{stdio:["ignore","pipe","pipe"]}),n="";(o=i.stderr)==null||o.on("data",a=>{n+=a.toString()}),i.on("error",a=>{r(new Error(`Failed to extract tgz file ${s}: ${a.message}. ${n}`))}),i.on("close",a=>{a!==0&&r(new Error(`Failed to extract tgz file ${s}: tar exited with code ${a}. ${n}`)),t()})}),il=s=>(0,at.statSync)(s).size/1e6;ol=async(s,e,t="sha256",r="hex")=>{let i=await tl.promises.readFile(s),n=Qm.createHash(t).update(i).digest(r);if(n!==e)throw await tl.promises.unlink(s),new Error(`Checksum mismatch for ${s}. Expected ${e}, got ${n}`)}});var qt={};q(qt,{APPIUM_SESSION_MESSAGE:()=>dl,CLI_MODE:()=>J,MOBILE_APP_SOURCE:()=>Hn,MOBILE_RUN_SKIP_REASON:()=>pl,OPERANDS:()=>si,REGION_CONFIG:()=>Yr,SEGMENT_CONFIG:()=>Qr,X_HEADER_RUNNER_ID:()=>ml,gridMessages:()=>bt,gridTypes:()=>N,mobileWeb:()=>ll,runnerStatus:()=>cl,runnerTestStatus:()=>he,socketEventTypes:()=>Lt,stepResult:()=>Xr,test:()=>ul,testRunStatus:()=>ri,testStatus:()=>Qe,timeoutMessages:()=>Ae});var Ae,ri,cl,he,Qe,bt,ll,ul,Lt,J,N,Xr,Hn,pl,dl,ml,Yr,Qr,si,oe=I(()=>{"use strict";Ae={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout",TEST_REACHED_CUSTOM_TIMEOUT_MSG:"test-reached-custom-timeout"},ri={COMPLETED:"completed"},cl={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},he={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Qe={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},bt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},ll={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},ul={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Lt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},J={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},N={LOCAL:"local",TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC"},Xr={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error",KEEP_ALIVE_FAILED:"keep-alive-failed"},Hn={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},pl={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},dl={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"},ml="X-Testim-Runner-ID",Yr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"},Qr={TTL:1e3*60*60*72,CACHE_FN_NAME:"setSegmentConfig"},si=(t=>(t.AND="AND",t.OR="OR",t))(si||{})});function ii(s,e){var t,r,i,n,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(i=s.browser)==null?void 0:i.toLowerCase()]:(n=s.testConfigNames)!=null&&n.length||(o=s.testConfigIds)!=null&&o.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(c=>{var l;return(l=c.runConfig)==null?void 0:l.browserValue}))]:[(a=s.browser)==null?void 0:a.toLowerCase()]}function Ev(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var ni,ef,Ze,Iv,Rv,xv,Cv,Av,fl,gl,tf=I(()=>{"use strict";oe();ni=s=>{var e,t;return!!((e=s.testPlan)!=null&&e.length||(t=s.testPlanIds)!=null&&t.length)},ef=s=>!!(s.resultId&&s.source==="remote-run"),Ze=(s,e)=>s.testStatus===Qe.QUARANTINE&&!ef(e)&&!e.runQuarantinedTests;Iv=s=>!!s.loginMode,Rv=s=>!!s.tunnelOnlyMode,xv=s=>!!s.createPrefechedData,Cv=s=>!!s.installLazyDepsMode,Av=s=>!!s.agentMode,fl=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},gl=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function zn(s=0){return qn.default.duration(s).format("HH:mm:ss.SSS")}function hl(s=0){return qn.default.duration(s).asSeconds()}var qn,rf,Kn,sf=I(()=>{"use strict";qn=R(require("dayjs")),rf=R(require("dayjs/plugin/duration"));qn.default.extend(rf.default);Kn=s=>{let e=Math.floor(s.asMinutes()),t=s.asSeconds()%60||0;return e>0?`${e} min ${Math.floor(t)} sec`:`${Math.floor(t)} sec`}});var oi,Zr,ir,nf,es,of=I(()=>{"use strict";oe();oi=s=>!(!s||"fileName"in s),Zr=(s,e)=>{if(e===N.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},ir=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},nf=s=>s===N.TESTIM_TVC,es=(s,e)=>nf(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function yl(s=4e3){let e=process.memoryUsage(),t=r=>Math.round(r/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>s,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var af=I(()=>{"use strict"});function lf(s){let e=(0,cf.default)(s);return e.validForNewPackages||e.validForOldPackages}function bl(s){let e=s.filter(t=>!lf(t.packageName)).map(t=>t.packageName);return e.length>0?e:null}function Tl(s){let e=s.filter(t=>t&&(t.includes("../")||t.includes("..\\"))).map(t=>t);return e.length>0?e:null}var cf,wl=I(()=>{"use strict";cf=R(require("validate-npm-package-name"))});var Y={};q(Y,{OSS:()=>ts,TESTIM_BROWSER_DIR:()=>Tt,buildBasicHeader:()=>Ic,calcPercentile:()=>Yn,copyDir:()=>Zm,delay:()=>ie,doesPathExist:()=>Te,download:()=>Ht,downloadAndSave:()=>Xe,extractElementId:()=>Ue,extractTgz:()=>sl,formatTimeoutDuration:()=>Kn,getArgsOnRemoteRunFailure:()=>Ev,getBrowserInfo:()=>kv,getCdpAddressForHost:()=>Ir,getCliLocation:()=>yt,getDuration:()=>zn,getDurationSec:()=>hl,getEnginesVersion:()=>nl,getEnvironmentGitBranch:()=>Er,getInvalidPackageNames:()=>bl,getInvalidPackagePaths:()=>Tl,getLinksFromUnescapeHTML:()=>li,getLocalFileSizeInMB:()=>il,getMemorySnapshot:()=>yl,getPlanType:()=>Xn,getRunConfigByBrowserName:()=>ai,getRunnerVersion:()=>it,getSource:()=>Gn,getSourceAsBuffer:()=>rl,getSourcePath:()=>Vn,getTestUrl:()=>ze,getUniqBrowsers:()=>ii,groupTestsByRetries:()=>Sl,guid:()=>ce,hasTestPlanFlag:()=>ni,isAgentMode:()=>Av,isAppFromDevice:()=>oi,isAppFromDeviceDisabled:()=>es,isCreatePrefetchedDataMode:()=>xv,isInstallLazyDepsMode:()=>Cv,isLoginMode:()=>Iv,isMobileProject:()=>ir,isPromise:()=>Hc,isQuarantineAndNotRemoteRun:()=>Ze,isRemoteRun:()=>ef,isTestimVirtualGrid:()=>nf,isTunnelOnlyMode:()=>Rv,isURL:()=>De,isValidPackageName:()=>lf,maskObjectFields:()=>Gc,maskSecret:()=>gf,promiseAbort:()=>qc,promiseFromCallback:()=>sr,promiseMap:()=>ne,promiseTimeout:()=>ae,removePropertyFromObject:()=>Jn,replaceArgsWithNoDashes:()=>fl,sanitizeNumberValue:()=>Sr,shouldBlockVirtualIosBuild:()=>Zr,spreadObjectToArgs:()=>gl,unescapeHTML:()=>ci,unzipFile:()=>Ye,verifyChecksum:()=>ol});function Sr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function kv(s){return s=s.toLowerCase(),vl.find(e=>e.browserValue===s)}function ai(s,e,t){s=s==null?void 0:s.toLowerCase();let r=vl.find(n=>n.browserName.toLowerCase()===s||s.includes(n.synonyms))||vl[0],i=ts.find(n=>n.osName==="Windows 10");return e&&(e.platform?i=ts.find(n=>n.sl.platform===e.platform):e.platformName&&(i=ts.find(n=>n.sl.platformName===e.platformName))),t&&(t.os_version?i=ts.find(n=>n.bs.os_version===t.os_version):t.platform&&(i=ts.find(n=>n.bs.platform===t.platform))),rs.merge(r,i)}function Er(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH||process.env.GITHUB_BRANCH_NAME}function Jn(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Jn(s[r],e,t))}function Ue(s){return s.ELEMENT||s[Qt]}function Xn(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Sl(s=[]){return rs.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=[...t].sort((n,o)=>{let a=typeof n.retryCount=="number"?n.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?n.startTime-o.startTime:(n.retryCount??0)-(o.retryCount??0)}),i=rs.cloneDeep(r.at(-1));return i&&(i.retryTestResults=r,e.push(i)),e},[]).compact().value()}function ci(s){return ff.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function li(s){return[...ff.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function Ir(s,e){let t=await Promise.resolve().then(()=>(We(),Je));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}function gf(s,{visiblePrefixLength:e=1,visibleSuffixLength:t=0,maskCharacter:r="*"}={}){if(!(s!=null&&s.length))return"";if(s.length-(e+t)<s.length*.8)return"".padEnd(s.length,r);let o=s.slice(0,e),a=s.slice(s.length-t);return`${o}${r.repeat(Math.ceil(s.length*.9))}${a}`}function Gc(s,e){let t=new Set(e),r=i=>{if(!(i===null||typeof i!="object")){if(Array.isArray(i)){i.forEach(n=>r(n));return}for(let n of Object.keys(i))if(t.has(n)){let o=i[n];o!=null&&(i[n]=gf(String(o)))}else typeof i[n]=="object"&&r(i[n])}};return r(s),s}var pf,rs,df,mf,Pv,Tt,uf,ts,vl,Yn,ff,U=I(()=>{"use strict";pf=R(require("os")),rs=R(require("lodash")),df=R(require("path")),mf=require("linkedom");Gr();al();tf();sf();Rc();zc();of();af();wl();Pv=pf.homedir(),Tt=df.join(Pv,".testim-browser-profile"),uf="133",ts=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"MacOS Tahoe",bs:{os:"OS X",os_version:"Tahoe",safari_version:"26.2"},sl:{},lt:{platform:"MacOS Tahoe"}},{osName:"MacOS Sequoia",bs:{os:"OS X",os_version:"Sequoia",safari_version:"18.4"},sl:{platform:"macOS 15",safari_version:"latest"},lt:{platform:"MacOS Sequoia"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17.3"},sl:{platform:"macOS 14",safari_version:"latest"},lt:{platform:"macOS Sonoma"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"},lt:{platform:"macOS Big Sur"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{},lt:{platform:"macOS Catalina"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{},lt:{platform:"macOS Mojave"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{},lt:{platform:"macOS High Sierra"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{},lt:{platform:"macOS Sierra"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{},lt:{platform:"OS X El Capitan"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{},lt:{platform:"OS X Yosemite"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{},lt:{platform:"OS X Mountain Lion"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],vl=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:uf},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:uf},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Yn=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,i)=>r-i),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};ff=new mf.DOMParser});var El={};q(El,{$schema:()=>Ov,default:()=>Mv,definitions:()=>_v,properties:()=>Nv,required:()=>Dv,type:()=>Lv});var Ov,_v,Lv,Dv,Nv,Mv,hf=I(()=>{Ov="http://json-schema.org/draft-07/schema#",_v={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},Lv="object",Dv=["entries"],Nv={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Mv={$schema:Ov,definitions:_v,type:Lv,required:Dv,properties:Nv}});async function Ef(){try{return await ae(Qn.promises.readFile(ro()).then(async s=>{let e=await Sf;return Bv(e,s)}),3e4)}catch{return{}}}function Bv(s,e){let t=e.slice(0,16),r=e.slice(16),i=Buffer.from(s),n=is.createDecipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),t),o=n.update(r);return JSON.parse(Buffer.concat([o,n.final()]))}function ct(s,e,t=Fv,r=void 0){return async()=>{if(!Tf)return await s();let i=e;r&&(e+=JSON.stringify(r));let n=await ns(e);if(n)return ui.debug("cache hit:",{fnName:e}),n;if(ui.debug("cache miss:",{fnName:e}),!wf)throw new Error(`Attempted to rebuild cache for ${i}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await jv(e,o,t),o}}async function ns(s){let t=(await so)[s];if(!t)return;let{value:r,expiry:i}=t;if(!(i<Date.now())&&r)return r}async function jv(s,e,t){if(Il)throw ui.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await so;r[s]={value:e,expiry:Date.now()+t},vf=new Promise(i=>{to=i}),Uv(r)}catch{ui.error("failed updating cache")}}async function os(){let s=await so;Object.keys(s).forEach(e=>{delete s[e]})}function If(s){Tf=s}function $v(s=!0){wf=s}async function Rf(){try{return Il=!0,await vf}finally{Il=!1}}function xf(s){eo=s,so=Ef()}var Qn,Zn,is,yf,ui,eo,bf,to,Tf,wf,Il,vf,Sf,Fv,ro,so,Uv,Cf,Af,PC,Pf,zt=I(()=>{"use strict";Qn=R(require("fs")),Zn=R(require("path")),is=R(require("crypto"));U();yf=require("lodash");W();ui=A("local cache"),eo=Zn.resolve(yt(),"testim-cache"),Tf=!0,wf=!0,Il=!1,vf=new Promise(s=>{to=s}),Sf=new Promise(s=>{bf=s}),Fv=1e3*60*60*3,ro=()=>Zn.resolve(Zn.resolve(eo,"testim.cache"));so=Ef(),Uv=(0,yf.debounce)(async s=>{let e;try{let t=await Sf,r=is.randomBytes(16),i=JSON.stringify(s),n=Buffer.from(t),o=is.createCipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(i),o.final()]);await Te(eo)||await Qn.promises.mkdir(eo,{recursive:!0}),await Qn.promises.writeFile(ro(),a)}catch(t){ui.error("failed saving cache",{err:t}),e=t}to(e?{success:!1,error:e}:{success:!0})},200);Cf=bf,Af=If.bind(void 0,!1),PC=If.bind(void 0,!0),Pf=()=>$v(!1)});function io(){return{cliLocation:yt(),userInfo:as.userInfo(),platform:as.platform(),release:as.release()}}var as,Rl=I(()=>{"use strict";as=R(require("node:os"));U()});function Wv(s){try{return no.resolve(no.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function or(s){let e=Wv(s);return require(e)}var no,pi=I(()=>{"use strict";no=R(require("path"))});function Vv(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Gv(s){return/The "to" argument must be of type string./.exec(s)}function Lf(s,e,t){let r=Vv(s),i=Gv(s);return r||i?(_f.info("Failed to install package due to insufficient write access",{...io(),package:t,path:r}),console.error(`
|
|
5
5
|
|
|
6
6
|
Testim failed installing the package ${t||""} due to insufficient permissions.
|
|
7
7
|
This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
|
|
8
|
-
Testim had missing write access to ${
|
|
8
|
+
Testim had missing write access to ${r||e}
|
|
9
9
|
|
|
10
|
-
`),!0):!1}function
|
|
10
|
+
`),!0):!1}function xl(s){try{return or(s)}catch{return!1}}function Df(s,e){let t=di.join(s,`./node_modules/${e}/package.json`);return JSON.parse(cs.readFileSync(t,"utf-8")).version}function Nf(s){if(typeof s=="string"&&s.endsWith(".cjs"))return s;if(typeof s=="object"&&s!==null)for(let e of Object.keys(s).filter(t=>t!=="browser")){let t=Nf(s[e]);if(t)return t}}function Mf(s){let e=di.join(s,"package.json"),t=JSON.parse(cs.readFileSync(e,"utf-8"));if(!("exports"in t))return"";let r=Nf(t);if(!r)throw new $n(t.name);return r}async function ao(s,e,t){let r=di.join(s,"npm-shrinkwrap.json"),i=di.join(s,"npm-shrinkwrap-dummy.json"),n=!1;try{try{await Te(r)&&(await cs.promises.rename(r,i),n=!0)}catch{}return await Of(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw Lf(o.stderr,s,e)?new Kr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(n)try{await cs.promises.rename(i,r)}catch{}}}function Cl(s,e,t,r,i=!0){return new Promise((n,o)=>{var h,g,b,T;let a=t?["--proxy",t]:[],c=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},l="",d="",m=["--no-save","--no-package-lock","--no-prune","--no-audit","--progress=false"];i&&m.push("--prefer-offline");let p="npm";process.platform==="win32"&&(p="npm.cmd",c.shell=!0);let f=(0,oo.spawn)(p,["i","--prefix",s,...m,...e,...a],c);(h=f.stderr)==null||h.pipe(process.stderr),(g=f.stdout)==null||g.pipe(process.stdout),(b=f.stdout)==null||b.on("data",v=>{l+=v}),(T=f.stderr)==null||T.on("data",v=>{d+=v}),f.on("close",v=>{var y,w;if(v){i&&Cl(s,e,t,r,!1).then(n).catch(o);let S;try{let x=(y=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(d))==null?void 0:y[1],_=(w=/No matching version found for (\S+)@/gm.exec(d))==null?void 0:w[1];x||_?S=`404 Not Found - GET https://registry.npmjs.org/${_??x} - Not found`:Lf(d,s)?S=`insufficient write access in location ${s}`:S=`Npm Installation closed with exit code ${v} with error: ${d}`}catch(x){S=`Npm Install closed with exit code ${v}
|
|
11
11
|
err: ${x}
|
|
12
|
-
stdout: ${l} stderr: ${d}`}
|
|
12
|
+
stdout: ${l} stderr: ${d}`}_f.info(`Npm Install closed with exit code ${v}`,{message:S,stderr:d}),o(new _t(S))}else n(l)}),setTimeout(()=>{try{f.kill()}finally{o(new ue)}},r)})}async function Ff(){try{return(await Of("npm -v")).stdout.trim()}catch{return""}}var cs,di,kf,oo,Of,_f,ls=I(()=>{"use strict";cs=R(require("fs")),di=R(require("path"));U();kf=require("util"),oo=require("child_process");W();Rl();pi();Q();Of=(0,kf.promisify)(oo.exec),_f=A("cli-service")});var $f={};q($f,{install:()=>qv,isReady:()=>Kv,start:()=>zv});var Uf,Bf,jf,kl,Pl,Hv,qv,zv,Kv,Wf=I(()=>{"use strict";Uf=R(require("fkill")),Bf=R(require("p-retry"));ls();We();U();pi();pe();jf="chromedriver",kl=9515,Pl=`http://localhost:${kl}/wd/hub`,Hv=[`--port=${kl}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],qv=async()=>{let s=O.flags.chromedriverCdnBinariesUrl.getValue(),e=De(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await ao(yt(),`${jf} --detect_chromedriver_version ${e}`)},zv=async()=>{process.env.NODE_OPTIONS="",await(0,Uf.default)(`:${kl}`,{silent:!0}),await or(jf).start(Hv,!0)},Kv=async({chromeBinaryLocation:s})=>{await(0,Bf.default)(async()=>{var i;let e=await ve(`${Pl}/status`);if(!((i=e==null?void 0:e.value)!=null&&i.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await $e({url:`${Pl}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!r||r.status!==0||!r.sessionId)throw new Error("create session failed");await ei(`${Pl}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var fi={};q(fi,{getSessionPlayerFolder:()=>Dl,prepareChromeDriver:()=>mi,prepareCustomExtension:()=>_l,prepareExtension:()=>Ll,preparePlayer:()=>Rr});async function _l(s,e=!1){if(!s)return;if(De(s)){let i=us.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Jv(s)>Ol&&!e)throw new C(Vf);return await Xe(s,i),i}let t=us.resolve(s);if(!Hf.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(il(t)>Ol&&!e)throw new C(Vf);return t}async function Jv(s){let e=(We(),Me(Je));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw co.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function Ll(s){co.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Vn(t)}));return ct(()=>ne(e,({location:t,path:r})=>Gn(t,r)),"prepareExtension",zf,e)()}async function mi(s={},e={},t=!1){let i=require("ora")("Starting Driver").start(),n=await Promise.resolve().then(()=>(Wf(),$f));try{await n.install(),await n.start(),t||await n.isReady(e),i.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof Kr||(co.error(a,{...s,...io(),error:(0,qf.serializeError)(o)}),console.log(`
|
|
13
13
|
1. If you don't have Chrome, please install it from https://www.google.com/chrome.
|
|
14
14
|
2. If Chrome is installed, please verify it's binary directory:
|
|
15
15
|
- installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
|
|
16
16
|
- exists in your PATH environment variables.
|
|
17
17
|
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").
|
|
18
|
-
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),o}}async function oS(){let r=`${er}/sessionPlayer_LATEST_RELEASE`;return(await qt(r)).body.toString("utf8")}async function aS(r,e){if(!De(r)||De(r)&&e||Ue)return r;let t=await oS();return`${r}-${t}`}function Nl(){let r=Tt();return ps.resolve(r,"testim-bin")}function cS(){let r=Nl();return ps.resolve(r,"sessionPlayer.zip")}async function eg(r,e,t=!1){try{return await Hi(r,e),await Qe(e,Nl())}catch(s){if(t)throw s;return await eg(r,e,!0)}}async function xr(r,e){lo.info("prepare player",{location:r,canary:e});let t=cS();return lt(async()=>{let s=await aS(r,e);return await eg(s,t),{}},"preparePlayer",Zf,[r,e,t])()}var Xf,Yf,ps,Qf,lo,Zf,_l,Jf,Tn=I(()=>{"use strict";Xf=R(require("ms")),Yf=R(require("node:fs")),ps=R(require("node:path"));le();Kt();Qf=require("serialize-error");W();xl();Q();U();lo=A("prepare runner and testim start"),Zf=(0,Xf.default)("0.5 day"),_l=16,Jf=`The size of the custom extension is more than ${_l}MB`});function lS(){let r=wn.type().toLowerCase();return r==="darwin"?wn.arch()==="arm"?"mac_arm":"mac":r==="windows_nt"?wn.arch()==="x64"?"win64":"win32":"linux"}async function po(){let r=lS(),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 C(`Unsupported platform: ${r}`);let s=parseInt(vn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:s,win64:s},i={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},o=`${e}/${t[r]}/${vn}/${n[r]}.zip`,a=uo.join(Ml,n[r]),c=`${a}.zip`,l=uo.join(a,i[r]);if(await Te(l))return l;if(!await Te(c)){let m=(0,Fl.default)("Downloading Chromium").start();try{await tg.promises.mkdir(Ml),await Ye(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 Qe(c,Ml)}catch(m){let p=`Failed to extract Chromium: ${m.message}`;throw d.fail(p),new Error(p)}return d.succeed(),l}var tg,wn,uo,Fl,vn,Ml,Ul=I(()=>{"use strict";tg=R(require("fs")),wn=R(require("os")),uo=R(require("path")),Fl=R(require("ora"));Q();U();vn="1000968",Ml=uo.join(vt,`chrome-${vn}`)});async function ng(r,e){return Cr=r,Wl=e,await Bl()}function ig(r,e){Cr=e.projectId,Wl=e.token,Sn=e.userAccessKey,ut=r.token,In=Vl(ut),Rn=r.refreshToken,jl=r.ngrokToken,$l=r.isNgrokWhitelisted,rg=e.publicIp,sg=e.initializedFromCache}function pS(r=Cr,e=Wl){return lt(()=>(En.info("request to get cli token from server"),We({url:`${be()}/auth/token`,body:{projectId:r,token:e}})),"getTokenV3",uS*10,{projectId:r,token:e})()}async function dS(){En.info("request to refresh JWT cli token from server");let r=await We({url:`${be()}/auth/refreshToken`,body:{token:ut,refreshToken:Rn}});return ut=r.token,In=Vl(ut),r.refreshToken&&(Rn=r.refreshToken),ut}async function Bl(){try{let r=await pS();return En.info("successfully get cli token from server"),ut=r.token,In=Vl(ut),Rn=r.refreshToken,jl=r.ngrokToken,$l=r.isNgrokWhitelisted,ut}catch(r){throw r.message.includes("Unauthorized")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(En.error(`While trying to retrieve CLI token. caught error: ${r}`,{projectId:Cr}),new C(`While trying to retrieve CLI token, caught error: ${r}`))}}function Vl(r){return require("jsonwebtoken").decode(r).exp*1e3}async function Nt(){if(!In)return Bl();let r=O.flags.accessTokenExpiryMargin.getValue();if(In<Date.now()+4*r)try{return await dS()}catch(e){return En.error("failed to refresh token, executing fallback",e),Bl()}return ut}function mo(){return Rn}function Ar(){return ut?{uid:require("jsonwebtoken").decode(ut).id,ngrokToken:jl,isNgrokWhitelisted:$l}:{}}async function fo(){if(!Sn||!Cr)return;if(await Gl({userAccessKey:Sn,projectId:Cr}))return Sn;let e=`user access key "${Sn}" is invalid for project "${Cr}"`;throw new C(e)}function go(){return rg}function ho(){return sg}var En,ut,In,Rn,jl,$l,Cr,Wl,Sn,rg,sg,uS,pt=I(()=>{"use strict";le();Ve();Kt();Q();W();ye();ue();En=A("testim-custom-token"),Cr=null,Wl=null,uS=300*1e3});function mS(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=og.exec(r.host);return(e==null?void 0:e[2])||"https"}return""}function fS(r){let e=og.exec(r);return e==null?void 0:e[3]}function bo(r){var w,S,x,_,B,G,E,k,L,j,V;let e=r&&fS(r.host),t=r.port,s=r.path,n=r&&mS(r),i=r.token,o=r.slotId,a=(w=r.hybrid)==null?void 0:w.tunnel,c=(S=r.external)==null?void 0:S.user,l=(x=r.external)==null?void 0:x.key,d=r.type,m=d===N.HYBRID?a&&((G=(B=(_=r.hybrid)==null?void 0:_.external)==null?void 0:B[r.hybrid.tunnel])==null?void 0:G.user):c,p=d===N.HYBRID?a&&((L=(k=(E=r.hybrid)==null?void 0:E.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=(V=r.mobileTokens)==null?void 0:V.iosToken,v=r.apiUrl,y=r.isSupportGrid;return{host:e,port:t,path:s,protocol:n,accessToken:i,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 hS(r,e,t,s,n,i){var a;let o;try{o=await i()}catch(c){throw dt.error("failed to get grid",{projectId:r,companyId:e,err:c}),new Error(wt.UNKNOWN)}if(dt.info("get grid info",{...o,projectId:r,companyId:e}),!o||!["success","error"].includes(o.status))throw dt.error("invalid response - get grid",{res:o}),new Error(wt.UNKNOWN);if(o.status==="success"){if(o.grid.mode==="local")return{mode:"local"};((a=o.grid)==null?void 0:a.mode)==="custom"&&Object.assign(o.grid,ug(n));let c=bo(o.grid);return gS(t,e,c.gridId,c.slotId,s,c.isSupportGrid),c}throw o.code==="not-found"?new ot(wt.NOT_FOUND):o.code==="no-available-slot"?new sr(`Failed to run test on ${s} - concurrency limit reached`):(dt.error("invalid code error response - get grid",{res:o}),new ot(wt.UNKNOWN))}function cg(r){return Xl(r)}async function lg(r,e,t){let n=(t||await cg(r)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return bo(n)}async function yS(r,e,t){let n=(t||await cg(r)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return bo(n)}async function Hl(r,e){let t=xn[r];if(!t)return;let{slotId:s,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete xn[r],!a){if(!s){dt.warn("failed to find grid slot id",{projectId:e});return}dt.info("release slot id",{projectId:e,companyId:o,slotId:s,gridId:n,browser:i});try{await zl(o,e,s,n,i)}catch(c){dt.error("failed to release slot",{projectId:e,err:c})}}}async function bS(r){let e=Object.values(xn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid)try{await ql(r,e)}catch(t){dt.error("failed to update grid keep alive",{err:t,slots:e,projectId:r})}}function TS(r){ag=global.setInterval(bS,1e4,r)}async function wS(r){let e=Object.keys(xn);if(e.length){dt.warn("not all slots released before end runner flow",{projectId:r});try{await oe(e,t=>Hl(Number(t),r))}catch(t){dt.error("failed to release all slots",{err:t,projectId:r})}}}async function vS(r){await wS(r),clearInterval(ag)}function SS(r,e){let{testobjectSauce:t,saucelabs:s}=e;if(r==="testobject")return t.testobjectApiKey;if(r==="saucelabs")return s.accessKey}function ES(r,e){let{saucelabs:t}=e;if(r==="saucelabs")return t.username}function ug(r){let t=yo.isEmpty(r.testobjectSauce)?yo.isEmpty(r.saucelabs)?yo.isEmpty(r.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject",{host:s,port:n,path:i,protocol:o}=r,a=SS(t,r),c=ES(t,r);return{host:s,port:n,path:i,protocol:o,type:t,user:c,key:a,gridId:ne()}}async function pg(r,e){let t=r.company.companyId;return await lg(t,e.gridId,r.allGrids)}async function dg(r){let{allGrids:e,company:t,host:s,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:c}=r;if(n||o||i)return{mode:"local"};if(s)return ug(r);let l=t==null?void 0:t.companyId;if(a)return lg(l,a,e);if(c)return yS(l,c,e);if(ln(r)||r.tunnelOnlyMode){dt.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new ot("Missing host or grid configuration")}async function mg(r,e,t,s,n){let{host:i,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 hS(o,h,s,r,t,()=>Jl({projectId:o,companyId:h,browser:r,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:i,testResultId:n}))}var yo,dt,xn,og,ag,gS,Cn,fg,ds=I(()=>{"use strict";yo=R(require("lodash"));ye();W();U();ae();Q();dt=A("grid-service"),xn={},og=/(^(https?):\/{2})?(.*)/,ag=null;gS=(r,e,t,s,n,i)=>{xn[r]={gridId:t,companyId:e,slotId:s,browser:n,isSupportGrid:i}};Cn={start:TS,end:vS};fg=async(r={},e={},t={},s={},n={})=>{var g,b,T;let{company:{companyId:i}={},project:o}=r,{gridId:a,type:c}=e,l=r.browser||t.browserValue,d=!!r.tunnel,{maxRetries:m,currentRetry:p}=n;if(!a||!c||((c===N.TESTIM_LAMBDATEST||c===N.LAMBDATEST)&&await((g=s.enableIfNeeded)==null?void 0:g.call(s,e,i,o)),c!==N.HYBRID||!i||!l||!m||!p))return e;let f=await Kl({companyId:i,gridId:a,maxRetries:m,currentRetry:p,browser:l,usingTunnel:d});dt.info("handling hybrid grid",{response:f,companyId:i});let h=bo({...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,i,o)),h}});function Pn(){return To||"master"}function gg(r="master",e="false"){if(typeof r!="string"&&(r!=null&&r.branch)&&r.branch==="master"){To="master";return}if(r!=null&&r.isArchived)throw new C(`Branch ${r.branch} is archived, run aborted.`);if(r){To=r.branch||r;return}To=e?"master":void 0}var To,Yl=I(()=>{"use strict";Q()});function bg(r){if(!Ue){if(r!=null&&r.userId||(r={anonymousId:"runnerId"}),!St){os(Zr.CACHE_FN_NAME).then(e=>{St=new wo.Analytics({writeKey:e||yg,flushAt:1}),St.identify(r)});return}St.identify(r)}}function mt(r,e){return ms("ci",r,e)}function ms(r,e,t){if(Ue)return;let s=r?{userId:r}:{anonymousId:"runnerId"};if(!St){os(Zr.CACHE_FN_NAME).then(n=>{St=new wo.Analytics({writeKey:n||yg,flushAt:1}),St==null||St.track(Object.assign(s,{event:e,properties:t}))});return}St.track(Object.assign(s,{event:e,properties:t}))}function Tg(r){r&&(St=new wo.Analytics({writeKey:r,flushAt:1}),lt(async()=>r,Zr.CACHE_FN_NAME,Zr.TTL,{writeKey:r})())}var wo,yg,St,Pr=I(()=>{"use strict";le();Kt();wo=require("@segment/analytics-node");ae();yg="sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY"});var wg={};q(wg,{isCi:()=>fs});var fs,vo=I(()=>{"use strict";fs=!!(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID)});function Sg(r,e){return e!=null&&e.type&&(r[`${e.type}Mode`]=!0),r}function Eg({executionId:r,projectId:e,testId:t,resultId:s,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:l,user:d,lightweightMode:m,isStartUp:p,projectType:f,appSource:h,gridType:g}){let b=Sg({executionId:r,projectId:e,testId:t,resultId:s,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:vg(l,d),isStartUp:p,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);mt("test-run-ci",b)}function Ig({executionId:r,projectId:e,testId:t,resultId:s,result:n,ucid:i,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=Sg({executionId:r,projectId:e,testId:t,resultId:s,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:vg(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&b&&{appSource:b}},p);if(n.success){mt("test-run-ci-success",v);return}mt("test-run-ci-fail",{...v,failureReason:n.failureReason})}catch(v){f.error("failed to update test end analytics",{err:v})}}function Rg(r){mt("batch-run-ci",r)}var vg,Ql=I(()=>{"use strict";Pr();vo();vg=(r,e)=>r!=="cli"&&r!=="cli-local"?r:fs&&e?"ci-with-user":fs?"ci":e?"cli-with-user":r});var me,On,Cg=I(()=>{"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";On=me});var _n,Zl,IS,eu,RS,So,Eo,Io,Ro,xo,Co=I(()=>{"use strict";U();ae();_n=r=>{let{status:e,mobile:t}=r;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===he.FAILED},Zl=r=>{let{status:e}=r;return e===he.ABORTED},IS=r=>{let{status:e}=r;return e===he.PASSED},eu=r=>r.runnerStatus===ll.SKIPPED,RS=r=>r.testStatus===Ze.EVALUATING,So=(r,e)=>Object.values(r).filter(t=>{var s,n;return eu(t)&&(et(t,e)||((s=t.mobile)==null?void 0:s.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Eo=r=>Object.values(r).filter(e=>_n(e)&&RS(e)).length,Io=r=>Object.values(r).filter(_n),Ro=r=>Object.values(r).filter(IS),xo=r=>Object.values(r).filter(Zl)});function CS(r){let e=r.indexOf("--token");if(e!==-1)try{let t=r.slice();return t.splice(e,2),t}catch{}return r}var tu,Ao,xS,Po,Ag=I(()=>{"use strict";tu=R(require("lodash"));W();Co();Ao=A("debug-reporter"),xS=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],Po=class{constructor(e){this.options=e}onTestStarted(e,t){Ao.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let s=this.options.gridData||{},n=s.provider,i=s.host,o=s.gridId,a=s.type,c=s.failedGetBrowserAttempts;Ao.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:c,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...tu.default.omit(this.options,xS),company:tu.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,s,n,i,o,a){let c=CS(process.argv);Ao.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,s,n,i){let o=Ro(e).length,a=Object.keys(e).length-o;Ao.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:s})}}});var ru,Mt,Ln=I(()=>{"use strict";ae();ru=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}},Mt=new ru});var nu={};q(nu,{Reporter:()=>AS});var lr,Dn,kr,ko,Pg,su,AS,iu=I(()=>{"use strict";lr=R(require("chalk")),Dn=R(require("lodash"));U();ae();Ln();Co();kr={success:lr.default.green,warn:lr.default.yellow,error:lr.default.red},{CLI_MODE:ko}=zt,Pg="device",su=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})`,n=`url: ${lr.default.underline(Ke(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${s} ${n}`.trim())}onTestFinished(e,t){let s=e.success?he.PASSED:he.FAILED,n=`(${e.testId})`,i=kr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${s} ${n} duration: ${Ki(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(s=>{let n=Ke(this.options.editorUrl,this.options.project,s.testId,s.resultId,this.branchToUse);return`${s.name} : ${n}`});console.log(kr.error("Failed runs are:")),console.log(kr.error(t.join(`
|
|
19
|
-
\r`)))}onTestPlanFinished(e,t,s,n,i){let o=Io(e),a=Ro(e),c=xo(e),l=a.length,d=c.length,m=o.length,p="",f="";if(Mt.isTestStatusEnabled){let v=Eo(e);p=` FAILED-EVALUATING: ${v}`,m-=v,f=` SKIPPED: ${So(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,b=kr[m?"error":"success"],T=`PASSED: ${l} FAILED: ${m}${p} ABORTED: ${d}${f} Duration: ${Ki(s)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(b(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let s=Dn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Dn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Dn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Dn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,s,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,s,n,i,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}]`:et(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,n)} test plan with ${m} (${i})`),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,n=this.options.mode===ko.APPIUM?Pg:t;s&&console.log(this.toWorkerIdPrefix(e),`Get ${lr.default.underline(n)} slot from ${lr.default.underline(s)}`)}onGetSession(e,t,s){let n=s===ko.APPIUM?Pg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${lr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,s){if(s!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===ko.APPIUM?"device":"browser";if(n)console.log(kr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(kr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===ko.APPIUM?"Appium":"Selenium";console.log(kr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},AS=su});var cu={};q(cu,{Reporter:()=>DS});function PS(r){let e=r.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${r.name}${t}`}function kS(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 OS(r){return`${r.visitedUrlsJson||""}`}async function _S(r,e,t,s,n,i){function o(p){let f=Ke(r,t,p.testId,p.resultId,s),h={$:{name:PS(p),classname:n,time:yl(p.duration),ownedBy:p.testOwnerName,ownerEmail:p.testOwnerEmail},"system-out":f};if(_n(p)||Zl(p)){let g=`Step Failed: ${p.failureReason||p.reason}`,b=_n(p)?`${g} More info at: ${f}`:g;h.failure={$:{message:b}}}return eu(p)&&et(p,i)&&Mt.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=kS(p),h["visited-urls-json"]=OS(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(Mt.isTestStatusEnabled){v.skipped=So(b,i);let y=Eo(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 Io(p).length+xo(p).length}let m={testsuites:{testsuite:e.map(p=>a(p))}};try{return new au.Builder().buildObject(m)}catch(p){return LS(p)}}function LS(r){let e=new au.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 au,kg,ou,DS,lu=I(()=>{"use strict";au=R(require("xml2js"));U();kg=require("fs");Ln();Co();ou=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,n=await _S(this.options.editorUrl,e,s,this.branchToUse,this.classname,this.options);if(t)try{return await kg.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};DS=ou});var Og={};q(Og,{Reporter:()=>NS});function gs(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 uu,pu,NS,_g=I(()=>{"use strict";W();uu=A("team-city-reporter");pu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},s=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${s}`;return gs(n)}onTestStarted(e,t,s,n){if(s){uu.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,s,n,i,o){if(i){uu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${gs(t)}' details='${gs(s)}' flowId='${o}']`)}onTestFinished(e,t,s){if(s){uu.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,s="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${gs(s)}']`)}onTestPlanStarted(e,t,s,n){console.log(`##teamcity[testSuiteStarted name='${gs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${gs(t)}']`)}},NS=pu});var Lg={};q(Lg,{Reporter:()=>MS});var du,MS,Dg=I(()=>{"use strict";du=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,n,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},MS=du});function _o(r){let{platform:e}=process;e==="win32"?(0,Oo.exec)(`start chrome ${r}`):e==="darwin"?(0,Oo.exec)(`open -a "Google Chrome" ${r}`):e==="linux"&&(0,Oo.exec)(`google-chrome ${r}`)}var Oo,mu=I(()=>{"use strict";Oo=require("child_process")});var Ng={};q(Ng,{Reporter:()=>FS});var fu,FS,Mg=I(()=>{"use strict";U();mu();fu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=Ke(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return _o(t)}},FS=fu});var gu,Z,Ft=I(()=>{"use strict";Ag();gu=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 Po(e)),s===void 0||s.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(iu(),nu));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(lu(),cu));this.reporters.push(new i(e,t))}}else(await Promise.all([s.includes("teamcity")&&Promise.resolve().then(()=>(_g(),Og)),s.includes("console")&&Promise.resolve().then(()=>(iu(),nu)),s.includes("junit")&&Promise.resolve().then(()=>(lu(),cu)),s.includes("json")&&Promise.resolve().then(()=>(Dg(),Lg)),s.includes("chrome")&&Promise.resolve().then(()=>(Mg(),Ng))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,s,n,i){let o={};o=e;let a=Date.now()-(s||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...s)=>{var i;let n=t==null?void 0:t(...s);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||s))}}},Z=new gu});async function hu(r,e,t){let s=hs[r];if(!s)return;let{slotId:n}=s;if(delete hs[r],!n){Et.warn("failed to find slot slot id",{companyId:e,workerId:r});return}Et.info("release slot id",{companyId:e,slotId:n});try{await bu(e,t,n)}catch(i){Et.error("failed to release slot",{companyId:e,err:i})}}async function US(r,e){let t=Object.values(hs).filter(Boolean);if(t.length!==0)try{await wu(r,e,t)}catch(s){Et.error("failed to update slot keep alive",{err:s,slots:t,companyId:r})}}function BS(r,e){Fg=global.setInterval(()=>US(r,e),1e4)}async function jS(r,e){let t=Object.keys(hs);if(t.length){Et.warn("not all slots released before end runner flow",{companyId:r});try{await oe(t,s=>hu(Number(s),r,e))}catch(s){Et.error("failed to release all slots",{err:s,companyId:r})}}}async function $S(r,e){await jS(r,e),clearInterval(Fg)}async function Bg(r,e,t){let s;try{s=await yu(r,e)}catch(n){throw Et.error("failed to get slot",{companyId:r,err:n}),new Error(wt.UNKNOWN)}if(Et.info("get slot info",{...s,companyId:r}),!s||!["success","error"].includes(s.status))throw Et.error("invalid response - get slot",{res:s}),new Error(wt.UNKNOWN);if(s.status==="success")return Ug(t,{slotId:s.slotId}),s.slotId;throw s.code==="not-found"?new ot(wt.NOT_FOUND):s.code==="no-available-slot"?new sr("Failed to run test - concurrency limit reached"):(Et.error("invalid code error response - get slot",{res:s}),new ot(wt.UNKNOWN))}async function jg(r,e,t,s){let n=hs[s];if(!n)throw new Error("slot not found");Object.assign(n,t),Ug(s,n),await Tu(r,e,n),Et.info("update slot data on server",{companyId:r,projectId:e,slotData:t})}var Et,hs,Fg,Ug,Nn,ys=I(()=>{"use strict";ye();W();U();ae();Q();Et=A("slot-service"),hs={},Fg=null,Ug=(r,e)=>{hs[r]=e};Nn={start:BS,end:$S}});function Wg(r,e=process){async function t(s){await ce(oe($g,async n=>n()),1e4).catch(()=>null),r(s)}e.on("uncaughtException",async s=>{s.message.includes("Command browsingContext")||(Fn.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 n;if(Fn.fatal("Caught unhandled promise rejection",s),!((n=s==null?void 0:s.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw s}),e.on("rejectionHandled",()=>{Fn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let s="Runner aborted - SIGTERM event",n=new Error(s);throw Fn.error(s),t(n),n}),e.once("SIGINT",()=>{let s="Runner aborted - SIGINT event",n=new Error(s);throw Fn.error(s),t(n),n}),e.once("exit",s=>{r(s)})}function bs(r){$g.push(r)}var Fn,$g,Un=I(()=>{"use strict";W();U();Fn=A("process-handler"),$g=[]});var qg={};q(qg,{installAllLazyDependencies:()=>HS,lazyRequire:()=>Ne});async function Ne(r,e={}){let t=Cl(r);if(t)return t;let s;e.silent||(s=(0,Vg.default)(`Installing ${r} before first usage...`).start());try{let n=await GS(r);return s&&s.succeed(),n}catch(n){VS.warn("failed to install dependency lazily",{dependency:r,err:n});let i=Hg(r),o=`${r}@${i}`,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),n}}async function GS(r){return Ts.has(r)||(Ts.set(r,Gg(r)),Ts.get(r).catch(()=>{Ts.delete(r)})),Ts.get(r)}async function Gg(r){let e=Cl(r);if(e)return e;let t=Hg(r),s=`${r}@${t}`;return await co(Tt(),s),ar(r)}async function HS(){let r=Object.keys(Ac);for(let e of r)await Gg(e)}function Hg(r){let e=Object.entries(Ac).find(([t])=>t===r);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Vg,VS,Ts,ws=I(()=>{"use strict";Vg=R(require("ora"));us();W();U();Oi();gn();VS=A("lazy-require"),Ts=new Map});var zg,Lo,Kg=I(()=>{"use strict";zg=require("istanbul-lib-report"),Lo=class extends zg.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 Jg,Xg,Yg,Bn,It,Qg,Do,vu,Zg,qS,eh,th,zS,KS,rh,JS,XS,YS,QS,ZS,sh,nh=I(()=>{"use strict";Jg=R(require("ora")),Xg=R(require("dayjs")),Yg=R(require("test-exclude")),Bn=R(require("fs")),It=R(require("path")),Qg=R(require("istanbul-reports")),Do=R(require("istanbul-lib-report"));ye();Q();U();W();ws();Kg();vu=A("test-run-status"),Zg=r=>{try{return new URL(r)}catch{try{return new URL(`file://${r}`)}catch{return{}}}},qS=r=>!!Zg(r).search,eh=r=>r?Zg(r).pathname.substring(1):"",th=(r,e)=>{let t=eh(e);return!new Yg.default({relativePath:!1,include:r}).shouldInstrument(t)},zS=r=>r.substring(0,r.indexOf("?")),KS=async({source:r,sourceMapDir:e,sourceMapType:t})=>{let s=await Ne("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?s.fromMapFileSource(r,e):s.fromSource(r)},rh=(r,e)=>`${It.resolve(r,eh(e))}.js`,JS=async(r,e,t)=>{let{codeCoverageInclude:s}=r;await oe(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await oe(i.sources,async(o,a)=>{if(th(s,o))return;let c=rh(e,o);await Bn.promises.mkdir(It.parse(c).dir,{recursive:!0}),await Bn.promises.writeFile(c,i.sourcesContent[a])})})},XS={getPath(r){if(typeof r=="string")return r;let e=r.getQualifiedName();return r.isSummary()?e!==""?e+="/index.html":e="index.html":(qS(e)&&(e=zS(e)),e+=".html"),e},relativePath(r,e){let t=this.getPath(e),s=It.dirname(this.getPath(r));return It.posix.relative(s,t)},assetPath(r,e){return this.relativePath(this.getPath(r),e)}},YS=async(r,e,t,s)=>{let{codeCoverageReporter:n}=r,i={},o=Do.createContext({dir:t,coverageMap:e,watermarks:Do.getDefaultWatermarks(),sourceFinder:a=>{try{let c=rh(s,a);return Bn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new Lo({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:XS}),Qg.create(a,c).execute(o)}),i},QS=async(r,{source:e,sourceMap:t,functions:s})=>{let{codeCoverageInclude:n}=r;if(!t||t.sourcemap.sources.length===0)return;let o=(await Ne("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>th(n,a));return await o.load(),o.applyCoverage(s),o.toIstanbul()},ZS=async(r,e)=>{let{mergeProcessCovs:s}=await Ne("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await Eu(r,"testResult",`runId=${e}`)).data.docs;return await oe(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await jn(c,9e4);await oe(l,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await Su(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=s([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},sh=async(r,e,t,s)=>{if(!r.collectCodeCoverage)return;vu.info("start js coverage process");let n=(0,Jg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=It.resolve(r.codeCoverageReportPath||"./coverage"),o=It.resolve(i,`.js/${(0,Xg.default)().format("DDMMYYYYHHmmss")}`),a=r.codeCoverageSourceMapPath?It.resolve(r.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([Ne("istanbul-lib-coverage"),ZS(r.project,s)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}vu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),p={};await oe(l.result,async({url:h,functions:g})=>{let{text:b,sourceMapType:T}=d.get(h),v=await KS({sourceMapType:T,source:b,sourceMapDir:a});p[h]=v;let y=await QS(r,{source:b,sourceMap:v,functions:g});m.merge(y)}),await JS(r,o,p);let f=await YS(r,m,i,o);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof C?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),vu.error(l,{err:c})}}});var ih={};q(ih,{SELENIUM_PERF_MARKS:()=>ke,SeleniumPerfStats:()=>Or});var ke,eE,Or,vs=I(()=>{"use strict";U();ke={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},eE=["ALL",...Object.values(ke)],Or=class{constructor(){this.marks=Object.fromEntries(eE.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=ne();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`,Qi(s,50)],[`${t}_P95`,Qi(s,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var lh={};q(lh,{initServer:()=>sE,mapFilesToLocalDrive:()=>Ru});function Ru(r,e){try{r.failurePath=(r.failurePath||[]).map(t=>Object.assign(t,No[t.id]?{screenshot:No[t.id]}:{})),Object.keys(Mo).forEach(t=>{r.assets||={},r.assets[ch[t]]=Mo[t]}),r.assets||={},r.assets.screenshots=Object.values(No)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),r.failurePath||=[],r.assets||={},r.assets.screenshots||=[]}}async function sE({agentPort:r,agentBind:e,saveRCALocally:t}){let s=await Ne("multer"),n=typeof t=="string"?t:tE;await Iu.promises.mkdir(n,{recursive:!0});let i=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=$n.join(n,m.testResultId);try{await Iu.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=$n.extname(m);return d(null,`step_${p.stepId}_${p.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,ah.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(No[d.stepId]=c.file.path),d.testResultId&&rE.includes(d.subType)&&(Mo[d.subType]||=[],Mo[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 C(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return l(new C(`Port ${r} is already in use`));default:return l(p)}}})}var Iu,oh,$n,ah,tE,No,Mo,ch,rE,xu=I(()=>{"use strict";Iu=R(require("fs")),oh=R(require("os")),$n=R(require("path")),ah=R(require("express"));Q();ws();tE=$n.join(oh.tmpdir(),"testim/rca/"),No={},Mo={},ch={"test-log":"consoleLogs","har-file":"networkLogs"},rE=Object.keys(ch)});var ur,Cu,Wn,uh=I(()=>{"use strict";ur=R(require("lodash"));U();W();Cu=A("override-test-data-builder"),Wn=class{constructor(e,t,s){this.params=e;this.testInfoList=t;this.projectId=s}isObjectNotArray(e){return ur.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(e=!1){let{params:t,projectId:s}=this;return this.isObjectNotArray(t)&&t.overrideTestData!==void 0&&(this.isObjectNotArray(t.overrideTestData)&&!ur.isEmpty(t.overrideTestData)?(Object.keys(t.overrideTestData).forEach(n=>this.overrideSingleTest(n,t.overrideTestData[n])),delete t.overrideTestData):Cu.error("invalid overrideTestData",{overrideTestData:t.overrideTestData,projectId:s})),this.isObjectNotArray(t)&&t.overrideAllTestsData!==void 0&&(ur.isObject(t.overrideAllTestsData)&&!ur.isEmpty(t.overrideAllTestsData)?(this.testInfoList.map(i=>i.name).forEach(i=>this.overrideSingleTest(i,t.overrideAllTestsData)),delete t.overrideAllTestsData):Cu.error("invalid overrideAllTestsData",{overrideAllTestsData:t.overrideAllTestsData,projectId:s})),this.isArrayOfObjects(t)&&e&&this.testInfoList.map(i=>i.name).forEach(i=>this.overrideSingleTest(i,t)),this.testInfoList}overrideSingleTest(e,t){let{projectId:s}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}Cu.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 ur.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(n=>{let i=s.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),c=s[o],l=this.createNewTestItems(c,t);return s.splice(o,a-o+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((s,n)=>{let i=ne();return{...e,resultId:i,testData:{value:s,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Vn(r,...e){if(!(!r||typeof r!="function"))try{return await r(...e)||{}}catch(t){throw tt.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var pr,tt,nE,iE,oE,aE,Fo,ph=I(()=>{"use strict";pr=R(require("lodash"));U();ae();ds();ys();ye();Q();W();Ft();Un();nh();vs();xu();le();ue();uh();Ln();tt=A("test-run-status"),nE=Ir(),iE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,oE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,aE=it();Fo=class{constructor(e,t,s,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.userTestDataParams={};this.seleniumPerfStats=new Or;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData,this.userTestDataString=this.options.testDataString;let i=cn(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:Di||t.parallel||1,browser:i,gitBranch:nE,gitCommit:iE,gitRepoUrl:oE,runnerVersion:aE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,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:n,executionId:i,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:pr.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},ku({projectId:n,runId:i,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:s,testResult:y})}testStart(e,t,s,n){let i=this.getTestResult(s);return i.workerId=e,Z.onTestStarted(i,e,n,s),i}async updateTestStatusRunning(e,t,s){var l;let{project:n,remoteRunId:i,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Bo(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){tt.error("failed to upload test data artifact (runner)",{err:d})}let c=pr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,_r(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:i,testRetryKey:s})}async testStartReport(e,t,s){var i;if(et(e,this.options))return;let n=this.exportsGlobal;try{let o=await Vn(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token),a=Array.isArray(this.userTestDataParams)?{}:this.userTestDataParams||{},c=(i=e.config)!=null&&i.testDataPrioritized?e.config.testData:{};return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...a,...c,...this.beforeSuiteParams,...o},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,s),e}catch(o){throw tt.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,s,n,i){let o=this.testStart(e,t,s,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let s=this.getTestResult(e);s.config.gridInfo={...t,key:void 0,user:void 0},tt.info("on get grid info",{gridInfo:s.config.gridInfo})}reportTestStatus(e,t,s,n){let{name:i,testId:o,testStatus:a}=s,{resultId:c,success:l}=t;if(a===Ze.EVALUATING&&Mt.isTestStatusEnabled){Z.onTestIgnored(e,s,`test in ${Ze.EVALUATING} status`);return}if(l){Z.onTestPassed(i);return}Z.onTestFailed(s,s.failureReason,Ke(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,n,c)}calcResultText(e){return e.success?he.PASSED:he.FAILED}onTestIgnored(e,t){let s=this.getTestResult(t);Z.onTestIgnored(e,s,`test in ${Ze.QUARANTINE}`)}monitorMemoryUsage(e){let t=bl();t.isOverThreshold&&tt.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,s,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&Ru(o,tt),o.resultUrl=Ke(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Z.onTestFinished(o,e,i);let c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,s,n){var o;let i=s.exportsGlobal;try{try{await Vn(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){tt.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await _r(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:s.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw tt.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,s,n,i,o){let a=this.testEnd(e,t,s,n,i);return this.testEndReport(a,s,t,o)}getMobileRunSkippedReason(e,t,s){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=dl;return e&&(n=i),es(t,s)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,s=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g,b;let c=e.browser?pn(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=ts(O,n)&&un(a.nativeApp)&&!e.appId,d=ir(e)&&(es(a.nativeApp,n)||l),m=et(a,e)||d,p={testId:a.testId,testOptimization:a.testOptimization,status:m?he.SKIPPED:he.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ze.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,n)},config:{...this.execConfig,companyId: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(i)}async endKeepAlive(e,t,s){e==="redis"&&await Nn.end(s,t),e==="mongo"&&await Cn.end(t)}async executionStart(e,t,s,n,i){tt.info("execution started",{executionId:e,gridId:this.execConfig.gridId,gridHost:this.execConfig.gridHost,gridName:this.execConfig.gridName,gridType:this.execConfig.gridType,parallel:this.execConfig.parallel,runnerVersion:this.execConfig.runnerVersion,source:this.execConfig.source});let{options:o}=this,{remoteRunId:a,projectData:c,company:{companyId:l}={},slotService:d}=o;bs(()=>Promise.all([this.endKeepAlive(d,t,l),Uo("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:i}},p=this.userTestDataString,f=await Vn(new Function(p||""));if(f&&(this.userTestDataParams=f,Array.isArray(f))){let S=new Wn(f,pr.cloneDeep(this.testInfoList),t);this.testInfoList=S.overrideTestData(!0)}let h=await Vn(o.beforeSuite,m),g=new Wn(h,pr.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=pr.cloneDeep(this.testRunStatus);await oe(Object.keys(S),async B=>{var j;let G=S[B],E=(j=G.config)==null?void 0:j.testData,k=G.testId,L=await Bo(t,k,B,E,c.defaults);L&&(delete G.config.testData,G.config.testDataUrl=L)});let x=!!(o.useLocalChromeDriver||o.useChromeLauncher),_=Pu({executionId:e,projectId:t,labels:n||[],startTime:s,executions:S,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:x,intersections:o.intersections});return this.executionStartedPromise=_,_.catch(B=>tt.error(B)),_};try{await w()}catch(S){tt.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){pr.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,n=0,i=0,o=0;for(let{status:m,testStatus:p}of t)m===he.PASSED&&n++,m===he.SKIPPED&&i++,m===he.FAILED&&p===Ze.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await Vn(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:s,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),tt.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await sh(this.options,this.branchToUse,s,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Uo("FINISHED",e,this.options.project,s===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw tt.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,s,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await Au(e,["QUEUED"],t,s,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=s,a.success=n}return this.testRunStatus}}});function Ou(r){var i;let e=r.canary?"-master.zip":".zip",t=`${er}/testim-headless${e}`,s=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(i=r.company)==null?void 0:i.companyId,projectId:r.project,runnerEnvironment:Js});return s||(cE.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:r.resultId,executionId:r.executionId,projectId:r.project}),s=`${er}/testim-headless.zip`),!(r.ext||r.extensionPath)&&s&&(t=s,r.testimHeadlessExtensionDownloadUrl=s),{chrome:t,"edge-chromium":t}}function dh(r){let{chrome:e}=Ou(r);return e}function jo(r){let e=`${er}/sessionPlayer`;return r.canary?`${e}-master`:e}var cE,Gn=I(()=>{"use strict";le();ue();W();cE=A("runOptionsUtils")});function Ss(r){var n;let t=(n=new RegExp(`^\\b(${Object.values(_u).join("|")})`).exec(r))==null?void 0:n[0];return t||_u[rm]||"usw2"}var _u,fh,$o=I(()=>{"use strict";le();_u={"us-west-2":"usw2","eu-central-1":"euc1"},fh=Object.fromEntries(Object.entries(_u).map(([r,e])=>[e,r]))});function gh(r,e){if(e){if(!fE.has(e)){Hn.warn(`OS ${e} is not supported by LT`,{testResultId:r});return}return e}}var hh,yh,Jt,bh,Th,wh,Wo,vh,Hn,lE,uE,qn,pE,dE,mE,Xt,fE,Vo=I(()=>{"use strict";hh=R(require("ms")),yh=R(require("p-retry")),Jt=R(require("node:os")),bh=R(require("portfinder")),Th=R(require("node:child_process"));U();Ve();ye();wh=R(require("node:fs")),Wo=R(require("node:fs/promises")),vh=require("node:path");Q();W();Gn();ae();ue();U();$o();Hn=A("lambdatestService"),lE="https://downloads.lambdatest.com/tunnel/v3",uE={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"},qn=`${Jt.tmpdir()}/LT`,pE=`${qn}/LT`,dE=(0,hh.default)("15m"),mE="2560x1440",Xt=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){r.isLambdatestGrid(e)&&(r.lambdatestConfigPromise||=Lu(t,s),r.lambdatestConfig=await r.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?dE:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await Te(pE))return;let t=uE[Jt.platform()+Jt.arch()];if(!t)throw new Error(`tunnel on ${Jt.platform()+Jt.arch()} platform is not supported.`);let s=`${qn}.zip`;await Ye(`${lE}/${t}`,s),await Qe(s,qn)}static async chmodLtTunnel(e){if(!(Jt.platform()==="win32"||!await Te(e))){try{await Wo.access(e,wh.constants.X_OK);return}catch{}try{await Wo.chmod(e,"777")}catch(s){throw Hn.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 bh.getPortPromise(),{gridData:s={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;r.tunnelName=ne();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,api.coralogix.com,*.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(n&&i)l=[...l,"--user",n,"--key",i];else throw new C("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 C("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await r.delay(3e3),await r.chmodLtTunnel((0,vh.join)(qn,"LT")),r.tunnel=Th.spawn("./LT",l,{cwd:qn});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,yh.default)(()=>ve(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Hn.info("LT tunnel info",p)}catch(p){throw Object.assign(p,{stdoutResult:d,stderrResult:m}),Hn.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",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),r.tunnel.kill()})}getCapabilities(e,t,s,n,i,o,a,c){var x;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:gh(n,a==null?void 0:a.os)||gh(n,(x=o==null?void 0:o.lt)==null?void 0:x.platform)||l.platform||r.lambdatestConfig.PLATFORM,resolution:r.lambdatestConfig.RESOLUTION??mE,...t!=="safari"&&{version:l.version}};if(c!==J.APPIUM&&c!==J.SELENIUM&&!f){let _=Ou({canary:p});!h&&_[t]&&(m=[...m,_[t]]),h&&De(h)&&(m=[...m,h]),m.length||Hn.warn("No extension was loaded in LambdaTestService",{extUrls:_,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&De(g)&&(m=[...m,g]);let T=Ss(e.project||""),y={euc1:"eu"}[T],w=y?{region:y}:{};return{"LT:Options":{build:s,name:`${n} - ${i}`,...w,selenium_version:r.lambdatestConfig.SELENIUM_VERSION,timezone:r.lambdatestConfig.TIMEZONE,...l,...b,loadExtension:m,...d,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}},fE=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 Sh,gE,Go,Du=I(()=>{"use strict";Q();Sh=["platformName","platform","app","bundleId","appPackage","extensions"],gE=["selenium_version","protocol","host","port","path","build"],Go=(r,e)=>{let t=e==="lambdaTest"?[...Sh,...gE]:Sh,s=[],n=[r];for(;n.length;){let i=n.pop();for(let[o,a]of Object.entries(i))t.includes(o)&&s.push(o),a&&typeof a=="object"&&n.push(a)}if(s.length)throw new C(`Custom capabilities contains forbidden keys: ${s.join(", ")}`)}});function yE(r,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(r.desiredCapabilities,t),r}function Lh(r){return Ah.readFileSync(r,{encoding:"base64"})}function Dh(r,e,t,s){if(t!=null&&t.isLambdatestRun()&&De(r))return null;if(r){if(s)return r.endsWith(".zip")?(Qe(r,Rh),Rh):r;let n=Lh(r);Is.info(`adding extension: custom, path: ${r} length: ${n.length} hash: ${Fu(n)} current extension count: ${e.length}`),e.push(n)}return null}function Nh(r,e,t,s,n,i){if(n!=null&&n.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 Is.info(`adding extension: testim unpacked , path: ${p}`),t.push(f),null}let c=`testim-headless${r.canary?"-master.zip":".zip"}`;!r.extensionPath&&o&&(c=Lr.basename(o));let l=Lr.join(process.cwd(),c);if(i)return Qe(l,Ih),Ih;let d=Lh(l);return Is.info(`adding extension: testim zipped, path: ${l} length: ${d.length} hash: ${Fu(d)} current extension count: ${e.length}`),e.push(d),null}function bE(r,e,t,s,n,i,o,a){var g,b;let c=t.seleniumName||t.browserValue,l=[],d=[...Oh];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Nu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Nu.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(Mu(n)){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}Mu(n)&&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=Ho();T.length&&T.forEach(v=>d.push(`--disable-features=${v}`))}catch{}e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Nu.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(),Dh(s,l,o),a===J.EXTENSION&&Nh(e,l,d,i,o),l.length>0&&(m.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[c],h={MicrosoftEdge:"ms",chrome:"goog"}[c];return Xt.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(r.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(r.desiredCapabilities[`${h}:${f}`]=m),r}function wE(r,e,t){let s={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(s,{"browser.helperApps.neverAsk.saveToDisk":xh.join(","),"browser.helperApps.neverAsk.openFile":xh.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 Es(r){return`${r.width}x${r.height}`}function xE(r){let{platform:e}=r;if(!e)return Es(Ch);let t=e.split(" ")[1];return e.startsWith("Windows")&&RE.has(t)?Es(SE):e==="Linux"?Es(vE):e.startsWith("macOS")?Es(EE):Es(e==="OS X El Capitan"||e==="OS X Yosemite"?IE:Ch)}function CE(r,e,t){let{saucelabs:s}=r;if(s!=null&&s.browserVersion&&(s.version=s.browserVersion),s!=null&&s.username&&s.accessKey){let n={"sauce:options":{name:e}};if(n["sauce:options"].screenResolution=xE(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version;let i=s.appiumVersion||t.sl.appiumVersion;i&&(n["sauce:options"].appiumVersion=i);let o=["screenResolution","appiumVersion"];t.browserValue!=="safari"&&o.push("safari_version");let a=Ge.omit((0,kh.cloneDeep)(t.sl),o);return Ge.merge(a,n,s)}return Ge.merge(n,s)}return{}}function AE(r){let{runnerOptions:e}=r;if(Ge.isEmpty(e.browserstack))return{};let{projectData:t,testRunConfig:s,testId:n,testName:i,executionId:o,executionName:a}=r,c={buildName:`${a} - ${o}`,sessionName:`${i} - ${n}`,projectName:`${t.name} - ${t.projectId}`,...e.browserstack};return s&&s.browserValue==="safari"&&s.bs.safari_version&&(c.os_version=s.bs.safari_version,s.bs.safari_version==="10"&&Object.assign(c,{"safari.options":{technologyPreview:!0}})),c}function PE(r){return r.perfecto?r.perfecto:{}}function kE(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 OE(r,e={}){let{gridData:t={},gridUsername:s,gridPassword:n}=r,i=s||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=Rc(i,o)),a}function Ho(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(r=>r.trim().length)}function qo(r){var B,G,E,k;let{overrideConfiguration:e,browserOptions:t,testId:s,testName:n,testRunConfig:i,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=[...Oh],V={};t.headless&&j.push("--headless"),t.silentDebuggerExtensionApi&&j.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&j.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let re=Ho();re.length&&re.forEach(ge=>j.push(`--disable-features=${ge}`))}catch{}t.chromeExtraArgs&&t.chromeExtraArgs.forEach(re=>j.push(`--${re}`)),t.chromeBinaryLocation&&(V.binary=t.chromeBinaryLocation);let K,z=null;return f!==J.SELENIUM&&(K=Nh(t,L,j,null,p,g)),z=Dh(a,L,p,g),g&&j.push("--enable-unsafe-extension-debugging","--remote-debugging-pipe"),{logLevel:Eh,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:j,extensions:L,...V},browserName:"chrome",...g&&{webSocketUrl:!0}},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515,...g&&K&&{unzippedTestimExtensionPath:K},...g&&z&&{unzippedCustomExtensionPath:z}}}let{driverRequestTimeout:b,driverRequestRetries:T}=t,v=OE(t,o),y={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Eh,connectionRetryTimeout:b,connectionRetryCount:T,getSessionTimeout:Math.max(p.getSessionTimeout,t.getSessionTimeout),getSessionRetries:p.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0},...!Ge.isEmpty(v)&&{headers:v},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};if(Mu(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||(i==null?void 0:i.browserValue),x={runnerOptions:t,testId:s,testName:n,testRunConfig:i,executionId:c,executionName:l,projectData:d};Ge.merge(y.desiredCapabilities,CE(t,n,i),AE(x),PE(t),kE(t,S,w),p==null?void 0:p.getCapabilities(t,S,c,m,n,i,e,f));let _=null;switch(!t.ext&&!t.extensionPath&&((B=o.host)!=null&&B.endsWith(".testim.io"))&&!t.canary&&f===J.EXTENSION&&(S==="chrome"||S==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(_="/opt/testim-headless"),S){case"chrome":case"edge-chromium":y=TE(y,t,i,a,o,_,p,f);break;case"firefox":y=wE(y,t,p);break;case"safari":case"safari technology preview":y=yE(y,S);break;default:break}h?(Go(h,o.type),Ge.merge(y.desiredCapabilities,h)):Ge.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=re=>re[o.provider]||re[y.host]||re[L[y.host]],V=re=>{var ge,ze;return j(re)||re[(ge=y.desiredCapabilities)==null?void 0:ge.browserName]||re[(ze=y.desiredCapabilities)==null?void 0:ze.version]||re||{}},K=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),z=V(V(K));Object.keys(z).length&&(Is.info(`Adding custom capabilities: ${JSON.stringify(z)}`),Object.assign(y.desiredCapabilities,z))}catch(L){Is.error("Failed to load custom capabilities",{error:L,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(y.desiredCapabilities&&!y.capabilities&&(hE(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=(G=y.capabilities)==null?void 0:G.alwaysMatch,j=JSON.parse(JSON.stringify(y)),V=(E=j==null?void 0:j.capabilities)==null?void 0:E.alwaysMatch,K=re=>re.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(re=>{var ge,ze;V!=null&&V[re]&&(V[re].extensions=(ze=(ge=L==null?void 0:L[re])==null?void 0:ge.extensions)==null?void 0:ze.map(K))}),V!=null&&V.loadExtension&&(V.loadExtension=(k=L==null?void 0:L.loadExtension)==null?void 0:k.map(K));let z=require("node:util");console.log(z.inspect(j,{showHidden:!1,depth:null,colors:!0}))}return y}var Ah,Lr,Ph,Ge,kh,Is,Eh,Nu,Oh,_h,Ih,Rh,Fu,Mu,hE,TE,xh,Ch,vE,SE,EE,IE,RE,zo=I(()=>{"use strict";Ah=R(require("node:fs")),Lr=R(require("node:path")),Ph=R(require("node:crypto")),Ge=R(require("lodash"));U();le();W();cl();U();ue();ae();Vo();Du();kh=require("lodash"),Is=A("testim-desired-capabilities-builder"),Eh=Li?"debug":"silent",Nu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Oh=["--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"],_h=Lr.join(vt,"extensions"),Ih=Lr.join(_h,"testim-headless"),Rh=Lr.join(_h,"custom-extension"),Fu=(...r)=>Ph.createHash("sha256").update(r.join("")).digest("hex"),Mu=r=>r.type===N.DEVICE_FARM||r.type===N.HYBRID&&r.provider==="devicefarm",hE=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 n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{Is.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};TE=Ge.memoize(bE,(r,e,t,s,n,i)=>{let o=JSON.stringify(r.desiredCapabilities),a=JSON.stringify(Ge.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return Fu(o,a,c,s,l,i)}),xh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Ch={width:1920,height:1080},vE={width:1920,height:1200},SE={width:2560,height:1600},EE={width:2360,height:1770},IE={width:2048,height:1536},RE=new Set(["7","8","8.1","10","11"])});function Ut(r){var e,t,s,n,i,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"||((n=r.message)==null?void 0:n.match(/did not match a known command/))||((i=r.message)==null?void 0:i.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 Fh(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 Uu=I(()=>{"use strict"});function Bu(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 n(p,f){for(let h=p;h&&h!==p.ownerDocument;h=t(h))if(f(h))return h;return null}function i(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 i(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=i(p,"stroke-width");return!!g&&parseInt(g,10)>0}return i(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 i(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 Bu(f)}case"INPUT":if(r.type==="hidden")return!1;break;default:break}if(i(r,"visibility")!=="visible")return!1;let d=!!n(r,p=>Number(i(p,"opacity"))===0),m=!!n(r,p=>i(p,"display")==="none");return!(d||m||!o(r)||c(r))}var Uh=I(()=>{"use strict"});var Bh,jh,Bt,_E,LE,Ko,$h=I(()=>{"use strict";Bh=R(require("promise-queue")),jh=R(require("webdriverio"));le();$e();U();W();Hr();Uh();Uu();vs();Bt=A("WebDriverApi"),_E=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},LE={implicit:0,pageLoad:1,script:2},Ko=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:n}=this,i=t?t.toString().slice(0,2e3):"";throw Bt.warn("error from selenium",{err:e,testResultId:n,testName:s,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Pc!==void 0&&(e=Pc);let t=1/0;this.queue=new Bh.default(e,t)}async addToQueue(e){var s,n;let t=(s=this.seleniumPerfStats)==null?void 0:s.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async installExtensions(e){var s;let t=[e==null?void 0:e.unzippedTestimExtensionPath,e==null?void 0:e.unzippedCustomExtensionPath].filter(Boolean);for(let n of t)await((s=this.client)==null?void 0:s.send({method:"webExtension.install",params:{extensionData:{type:"path",path:n}}}))}async initClient(e,t,s,n,i){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()=>{Bt.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 jh.remote(e),this.client.on("dialog",async b=>{try{await b.accept()}catch{}}),n&&await this.installExtensions(i),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",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){s=a,n=c;break}}catch(a){if(a.message==="unknown error"){Bt.info("grid status is not supported by the grid",{testResultId:e});return}Bt.error("failed to get grid status",{error:a,testResultId:e});return}s&&typeof s=="object"&&"slots"in s&&(s==null||delete s.slots),Bt.info("grid status",{gridStatusMsg:i.message,ready:i.ready,browserNode:s,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){Bt.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(Ut(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.execute(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Ut(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let s=await((n=this.client)==null?void 0:n.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 i;return(i=this.client)==null?void 0:i.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(Be(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(n=>({value:n})),s=()=>this.execute(Bu,{ELEMENT:e,[Zt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return s();try{return await t()}catch(n){if(Ut(n))return this.unsupportedActions.add("elementIdDisplayed"),s();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Fh(e,this.isSafari(),Bt))})}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 i=[];return i[LE[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await s()}catch(i){if(Ut(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let s=function(n,i){window.scrollTo(n,i)};return this.execute(s,e,t)}async setValue(e,t){return await this.elementIdClear(Be(e)),await this.elementIdValue(Be(e),t)}async getViewportSize(e){let t=await this.execute(_E);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 i;return(i=this.client)==null?void 0:i.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 i;let t=(i=this.client)==null?void 0:i.$(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 n;try{n=await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:s})})}catch(i){if(i.message.includes("unexpected alert open")||i.message.includes("dialog detected"))await this.alertAccept().catch(o=>Bt.warn("failed to click on alert",{err:o})),n=await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:s})});else throw i}return{value:n}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var 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 n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}moveTo(e,t,s){let n={...typeof t=="number"&&{xOffset:t},...typeof s=="number"&&{yOffset:s}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let i=this.client.$(e);await this.client.action("pointer").move({origin:i}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var 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 n=Math.abs(e.width),i=Math.abs(e.height);s=async()=>await this.client.setWindowSize(n,i)}try{return await s()}catch(n){throw n}})}}setCookie(e,t,s,n,i,o,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:s,httpOnly:n,secure:i,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){Bt.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 Bt.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var dr={};q(dr,{getSessionPlayer:()=>ee,options:()=>$u});var Jo,$u,ju,ee,Se=I(()=>{"use strict";Jo=require("path");W();$u={playerPath:void 0},ee=()=>{if(ju)return ju;let r=($e(),Fe(je));r.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Tn(),Fe(bn)),t=e(),s=$u.playerPath?(0,Jo.resolve)($u.playerPath,"src/background/sessionPlayerInit.ts"):(0,Jo.join)(t,"sessionPlayer.js"),n=require(s);return r.log("getSessionPlayerRequire end"),ju=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(jm),n}});var Wh={};q(Wh,{doubleClick:()=>DE});var DE,Vh=I(()=>{"use strict";DE=function(r,e){let t=["pointerup","pointerdown","pointermove"],s=getLocatedElement(r.locatedElement);if(!s)throw new Error("element not found");let n=r.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};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{n.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(i)}catch(p){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:p.toString(),success:!1})}}});var zn={};q(zn,{dispatchFocus:()=>NE});function NE(r,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function s(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=s();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(r){let i=getLocatedElement(r);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Kn=I(()=>{"use strict"});var Kh={};q(Kh,{WebDriver:()=>Nr});async function BE(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 FE(s):void 0}catch(s){He.info("Error getting cdpAddress",s);return}}var xs,qh,zh,He,Rs,ME,Gh,FE,Dr,UE,Hh,Jn,Nr,Xn=I(()=>{"use strict";xs=R(require("lodash"));U();$e();zo();qh=R(require("p-retry")),zh=R(require("ua-parser-js"));Hr();W();Uu();$h();Q();ue();vs();He=A("webdriver"),[Rs,ME]=[0,2],{extractElementId:Gh,getCdpAddressForHost:FE}=X,Dr=()=>(Se(),Fe(dr)).getSessionPlayer().codeSnippets,UE=()=>(Se(),Fe(dr)).getSessionPlayer().locatorBuilderUtils,Hh=()=>(Se(),Fe(dr)).getSessionPlayer().utils,Jn=()=>(Se(),Fe(dr)).getSessionPlayer().positionUtils;Nr=class extends Ko{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,G,E,k,L,j,V,K;let{projectData:s,overrideConfiguration:n,browserOptions:i,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=!!((E=(G=(B=i==null?void 0:i.company)==null?void 0:B.activePlan)==null?void 0:G.premiumFeatures)!=null&&E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let S=qo({projectData:s,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:d,executionId:m,executionName:p,testResultId:f,lambdatestService:b,overrideConfiguration:n,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 x=g?0:1500,_=g?(()=>null):()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let z={unzippedTestimExtensionPath:S.unzippedTestimExtensionPath,unzippedCustomExtensionPath:S.unzippedCustomExtensionPath},re=await this.initClient(S,a,f,w,z);M("after initResult before getCdpAddress in init"),this.cdpUrl=await BE(re),M("after getCdpAddress in webdriver.js init"),He.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await ie(x),O.flags.dontFocusOnInit.isEnabled()||await _(),M("after focus and delay in webdriver.js init")}catch(z){let re=JSON.stringify(xs.omit(S,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));He.error("failed to init webdriver",{err:z,capabilitiesAsString:re});let ge=((L=(k=i==null?void 0:i.company)==null?void 0:k.activePlan)==null?void 0:L.plan)==="free";throw(j=z.stack)!=null&&j.includes("at startWebDriverSession")&&((V=z.message)!=null&&V.startsWith("Failed to create session"))&&((K=z.message)!=null&&K.includes("Timeout awaiting 'request'"))&&ge?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(z.message)?new Kr(z.message):/capabilit(y|ies)/.test(z.message)&&!/UND_ERR_HEADERS_TIMEOUT/.test(z.message)?new ji(z.message):/403 Forbidden/.test(z.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(z.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${z.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>xs.zip(i.slice(0,-1),i.slice(1)),s=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(s).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let s=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=ne();s(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,He.warn("close unexpected alert open"),await this.alertAccept().catch(c=>He.warn("failed to click on alert",{err:c}));return}if(He.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;He.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.handleThresholdBasedError(this.browserClosedCallbacks,a)}else this.generalKeepAliveFailures++,this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures>=3&&this.handleThresholdBasedError(this.keepAliveFailedCallbacks,a)}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}handleThresholdBasedError(t,s){t.forEach(n=>{try{n(s)}catch{}})}async switchToLocatedFrame(t){let s=await this.getElement(t);if(!s.value)throw new Error("Element not found");let n=Gh(s.value);return await this.switchFrame({ELEMENT:n,[Zt]:n}),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 $i:s}}async getElement(t){var i;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(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
20
|
-
var fn = ${
|
|
18
|
+
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 Xv(){let s=`${Zt}/sessionPlayer_LATEST_RELEASE`;return(await Ht(s)).body.toString("utf8")}async function Yv(s,e){if(!De(s)||De(s)&&e||Fe)return s;let t=await Xv();return`${s}-${t}`}function Dl(){let s=yt();return us.resolve(s,"testim-bin")}function Qv(){let s=Dl();return us.resolve(s,"sessionPlayer.zip")}async function Kf(s,e,t=!1){try{return await Gn(s,e),await Ye(e,Dl())}catch(r){if(t)throw r;return await Kf(s,e,!0)}}async function Rr(s,e){co.info("prepare player",{location:s,canary:e});let t=Qv();return ct(async()=>{let r=await Yv(s,e);return await Kf(r,t),{}},"preparePlayer",zf,[s,e,t])()}var Gf,Hf,us,qf,co,zf,Ol,Vf,gi=I(()=>{"use strict";Gf=R(require("ms")),Hf=R(require("node:fs")),us=R(require("node:path"));le();zt();qf=require("serialize-error");W();Rl();Q();U();co=A("prepare runner and testim start"),zf=(0,Gf.default)("0.5 day"),Ol=16,Vf=`The size of the custom extension is more than ${Ol}MB`});function Zv(){let s=hi.type().toLowerCase();return s==="darwin"?hi.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?hi.arch()==="x64"?"win64":"win32":"linux"}async function uo(){let s=Zv(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new C(`Unsupported platform: ${s}`);let r=parseInt(yi,10)>591479?"chrome-win":"chrome-win32",i={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},n={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},o=`${e}/${t[s]}/${yi}/${i[s]}.zip`,a=lo.join(Nl,i[s]),c=`${a}.zip`,l=lo.join(a,n[s]);if(await Te(l))return l;if(!await Te(c)){let m=(0,Ml.default)("Downloading Chromium").start();try{await Jf.promises.mkdir(Nl),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,Ml.default)("Extracting Chromium").start();try{await Ye(c,Nl)}catch(m){let p=`Failed to extract Chromium: ${m.message}`;throw d.fail(p),new Error(p)}return d.succeed(),l}var Jf,hi,lo,Ml,yi,Nl,Fl=I(()=>{"use strict";Jf=R(require("fs")),hi=R(require("os")),lo=R(require("path")),Ml=R(require("ora"));Q();U();yi="1000968",Nl=lo.join(Tt,`chrome-${yi}`)});async function Qf(s,e){return xr=s,Bl=e,await Ul()}function Zf(s,e){xr=e.projectId,Bl=e.token,bi=e.userAccessKey,lt=s.token,wi=jl(lt),vi=s.refreshToken,Xf=e.publicIp,Yf=e.initializedFromCache}function tS(s=xr,e=Bl){return ct(()=>(Ti.info("request to get cli token from server"),$e({url:`${be()}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",eS*10,{projectId:s,token:e})()}async function rS(){Ti.info("request to refresh JWT cli token from server");let s=await $e({url:`${be()}/auth/refreshToken`,body:{token:lt,refreshToken:vi}});return lt=s.token,wi=jl(lt),s.refreshToken&&(vi=s.refreshToken),lt}async function Ul(){try{let s=await tS();return Ti.info("successfully get cli token from server"),lt=s.token,wi=jl(lt),vi=s.refreshToken,lt}catch(s){throw s.message.includes("Unauthorized")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(Ti.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:xr}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function jl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Dt(){if(!wi)return Ul();let s=O.flags.accessTokenExpiryMargin.getValue();if(wi<Date.now()+4*s)try{return await rS()}catch(e){return Ti.error("failed to refresh token, executing fallback",e),Ul()}return lt}function po(){return vi}function Si(){return lt?{uid:require("jsonwebtoken").decode(lt).id}:{}}async function mo(){if(!bi||!xr)return;if(await $l({userAccessKey:bi,projectId:xr}))return bi;let e=`user access key "${bi}" is invalid for project "${xr}"`;throw new C(e)}function fo(){return Xf}function go(){return Yf}var Ti,lt,wi,vi,xr,Bl,bi,Xf,Yf,eS,wt=I(()=>{"use strict";le();We();zt();Q();W();ye();pe();Ti=A("testim-custom-token"),xr=null,Bl=null,eS=300*1e3});function sS(s){if(s.protocol)return s.protocol;if([N.TESTIM_PRIVATE,N.TESTIM,N.BROWSERSTACK,N.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([N.TESTIM_ENTERPRISE,N.TESTIM_LAMBDATEST,N.DEVICE_FARM].includes(s.type)){let e=eg.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function iS(s){let e=eg.exec(s);return e==null?void 0:e[3]}function yo(s){var w,S,x,_,B,G,E,k,L,j,V;let e=s&&iS(s.host),t=s.port,r=s.path,i=s&&sS(s),n=s.token,o=s.slotId,a=(w=s.hybrid)==null?void 0:w.tunnel,c=(S=s.external)==null?void 0:S.user,l=(x=s.external)==null?void 0:x.key,d=s.type,m=d===N.HYBRID?a&&((G=(B=(_=s.hybrid)==null?void 0:_.external)==null?void 0:B[s.hybrid.tunnel])==null?void 0:G.user):c,p=d===N.HYBRID?a&&((L=(k=(E=s.hybrid)==null?void 0:E.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:L.key):l,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,b=(j=s.mobileTokens)==null?void 0:j.androidToken,T=(V=s.mobileTokens)==null?void 0:V.iosToken,v=s.apiUrl,y=s.isSupportGrid;return{host:e,port:t,path:r,protocol:i,accessToken:n,slotId:o,gridId:h,tunnel:a,user:c,key:l,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:p,androidToken:b,iosToken:T,apiUrl:v,isSupportGrid:y}}async function oS(s,e,t,r,i,n){var a;let o;try{o=await n()}catch(c){throw ut.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(bt.UNKNOWN)}if(ut.info("get grid info",{...o,projectId:s,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,ig(i));let c=yo(o.grid);return nS(t,e,c.gridId,c.slotId,r,c.isSupportGrid),c}throw o.code==="not-found"?new nt(bt.NOT_FOUND):o.code==="no-available-slot"?new rr(`Failed to run test on ${r} - concurrency limit reached`):(ut.error("invalid code error response - get grid",{res:o}),new nt(bt.UNKNOWN))}function rg(s){return zl(s)}async function sg(s,e,t){let i=(t||await rg(s)).find(n=>n._id===e);if(!i)throw new C(`Failed to find grid id: ${e}`);return yo(i)}async function aS(s,e,t){let i=(t||await rg(s)).find(n=>(n.name||"").toLowerCase()===e.toLowerCase());if(!i)throw new C(`Failed to find grid name: ${e}`);return yo(i)}async function Wl(s,e){let t=Ei[s];if(!t)return;let{slotId:r,gridId:i,browser:n,companyId:o,isSupportGrid:a}=t;if(delete Ei[s],!a){if(!r){ut.warn("failed to find grid slot id",{projectId:e});return}ut.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:i,browser:n});try{await Gl(o,e,r,i,n)}catch(c){ut.error("failed to release slot",{projectId:e,err:c})}}}async function cS(s){let e=Object.values(Ei).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid)try{await Vl(s,e)}catch(t){ut.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}function lS(s){tg=global.setInterval(cS,1e4,s)}async function uS(s){let e=Object.keys(Ei);if(e.length){ut.warn("not all slots released before end runner flow",{projectId:s});try{await ne(e,t=>Wl(Number(t),s))}catch(t){ut.error("failed to release all slots",{err:t,projectId:s})}}}async function pS(s){await uS(s),clearInterval(tg)}function dS(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function mS(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function ig(s){let t=ho.isEmpty(s.testobjectSauce)?ho.isEmpty(s.saucelabs)?ho.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject",{host:r,port:i,path:n,protocol:o}=s,a=dS(t,s),c=mS(t,s);return{host:r,port:i,path:n,protocol:o,type:t,user:c,key:a,gridId:ce()}}async function ng(s,e){let t=s.company.companyId;return await sg(t,e.gridId,s.allGrids)}async function og(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:i,localTmaUrl:n,useChromeLauncher:o,gridId:a,grid:c}=s;if(i||o||n)return{mode:"local"};if(r)return ig(s);let l=t==null?void 0:t.companyId;if(a)return sg(l,a,e);if(c)return aS(l,c,e);if(ni(s)||s.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 ag(s,e,t,r,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 oS(o,h,r,s,t,()=>ql({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:n,testResultId:i}))}var ho,ut,Ei,eg,tg,nS,Ii,cg,ps=I(()=>{"use strict";ho=R(require("lodash"));ye();W();U();oe();Q();ut=A("grid-service"),Ei={},eg=/(^(https?):\/{2})?(.*)/,tg=null;nS=(s,e,t,r,i,n)=>{Ei[s]={gridId:t,companyId:e,slotId:r,browser:i,isSupportGrid:n}};Ii={start:lS,end:pS};cg=async(s={},e={},t={},r={},i={})=>{var g,b,T;let{company:{companyId:n}={},project:o}=s,{gridId:a,type:c}=e,l=s.browser||t.browserValue,d=!!s.tunnel,{maxRetries:m,currentRetry:p}=i;if(!a||!c||((c===N.TESTIM_LAMBDATEST||c===N.LAMBDATEST)&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e,n,o)),c!==N.HYBRID||!n||!l||!m||!p))return e;let f=await Hl({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=r.disable)==null||b.call(r)),f.provider==="lambdatest"&&await((T=r.enableIfNeeded)==null?void 0:T.call(r,h,n,o)),h}});function xi(){return bo||"master"}function lg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){bo="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){bo=s.branch||s;return}bo=e?"master":void 0}var bo,Kl=I(()=>{"use strict";Q()});function dg(s){if(!Fe){if(s!=null&&s.userId||(s={anonymousId:"runnerId"}),!vt){ns(Qr.CACHE_FN_NAME).then(e=>{vt=new To.Analytics({writeKey:e||pg,flushAt:1}),vt.identify(s)});return}vt.identify(s)}}function pt(s,e){return ds("ci",s,e)}function ds(s,e,t){if(Fe)return;let r=s?{userId:s}:{anonymousId:"runnerId"};if(!vt){ns(Qr.CACHE_FN_NAME).then(i=>{vt=new To.Analytics({writeKey:i||pg,flushAt:1}),vt==null||vt.track(Object.assign(r,{event:e,properties:t}))});return}vt.track(Object.assign(r,{event:e,properties:t}))}function mg(s){s&&(vt=new To.Analytics({writeKey:s,flushAt:1}),ct(async()=>s,Qr.CACHE_FN_NAME,Qr.TTL,{writeKey:s})())}var To,pg,vt,Ar=I(()=>{"use strict";le();zt();To=require("@segment/analytics-node");oe();pg="sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY"});var fg={};q(fg,{isCi:()=>ms});var ms,wo=I(()=>{"use strict";ms=!!(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID)});function hg(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function yg({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:n,companyName:o,projectName:a,companyPlan:c,source:l,user:d,lightweightMode:m,isStartUp:p,projectType:f,appSource:h,gridType:g}){let b=hg({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:n,companyName:o,projectName:a,companyPlan:c,source:gg(l,d),isStartUp:p,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);pt("test-run-ci",b)}function bg({executionId:s,projectId:e,testId:t,resultId:r,result:i,ucid:n,companyId:o,companyName:a,projectName:c,companyPlan:l,source:d,user:m,lightweightMode:p,logger:f,isStartUp:h,projectType:g,appSource:b,gridType:T}){try{let v=hg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:i.wasMockNetworkActivated,source:gg(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 Tg(s){pt("batch-run-ci",s)}var gg,Jl=I(()=>{"use strict";Ar();wo();gg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ms&&e?"ci-with-user":ms?"ci":e?"cli-with-user":s});var me,Ai,vg=I(()=>{"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,Xl,fS,Yl,gS,vo,So,Eo,Io,Ro,xo=I(()=>{"use strict";U();oe();Pi=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===he.FAILED},Xl=s=>{let{status:e}=s;return e===he.ABORTED},fS=s=>{let{status:e}=s;return e===he.PASSED},Yl=s=>s.runnerStatus===cl.SKIPPED,gS=s=>s.testStatus===Qe.EVALUATING,vo=(s,e)=>Object.values(s).filter(t=>{var r,i;return Yl(t)&&(Ze(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((i=t.mobile)==null?void 0:i.isAppForIosVirtualDevice))}).length,So=s=>Object.values(s).filter(e=>Pi(e)&&gS(e)).length,Eo=s=>Object.values(s).filter(Pi),Io=s=>Object.values(s).filter(fS),Ro=s=>Object.values(s).filter(Xl)});function yS(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Ql,Co,hS,Ao,Sg=I(()=>{"use strict";Ql=R(require("lodash"));W();xo();Co=A("debug-reporter"),hS=["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 r=this.options.gridData||{},i=r.provider,n=r.host,o=r.gridId,a=r.type,c=r.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{...Ql.default.omit(this.options,hS),company:Ql.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,i,n,o,a){let c=yS(process.argv);Co.info("Test Plan Started",{executionId:n,testPlanName:i,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,i,n){let o=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:r})}}});var Zl,Nt,ki=I(()=>{"use strict";oe();Zl=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 Zl});var tu={};q(tu,{Reporter:()=>bS});var ar,Oi,Pr,Po,Eg,eu,bS,ru=I(()=>{"use strict";ar=R(require("chalk")),Oi=R(require("lodash"));U();oe();ki();xo();Pr={success:ar.default.green,warn:ar.default.yellow,error:ar.default.red},{CLI_MODE:Po}=qt,Eg="device",eu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,i=`url: ${ar.default.underline(ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${i}`.trim())}onTestFinished(e,t){let r=e.success?he.PASSED:he.FAILED,i=`(${e.testId})`,n=Pr[e.success?"success":"error"];console.log(n(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${i} duration: ${zn(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let i=ze(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${i}`});console.log(Pr.error("Failed runs are:")),console.log(Pr.error(t.join(`
|
|
19
|
+
\r`)))}onTestPlanFinished(e,t,r,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: ${zn(r)}`;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 r=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,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,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),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,i=this.options.mode===Po.APPIUM?Eg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${ar.default.underline(i)} slot from ${ar.default.underline(r)}`)}onGetSession(e,t,r){let i=r===Po.APPIUM?Eg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${i} to run ${ar.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let i=this.options.grid||this.options.gridId,n=this.options.mode===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}`))}}},bS=eu});var nu={};q(nu,{Reporter:()=>IS});function TS(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function wS(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function vS(s){return`${s.visitedUrlsJson||""}`}async function SS(s,e,t,r,i,n){function o(p){let f=ze(s,t,p.testId,p.resultId,r),h={$:{name:TS(p),classname:i,time:hl(p.duration),ownedBy:p.testOwnerName,ownerEmail:p.testOwnerEmail},"system-out":f};if(Pi(p)||Xl(p)){let g=`Step Failed: ${p.failureReason||p.reason}`,b=Pi(p)?`${g} More info at: ${f}`:g;h.failure={$:{message:b}}}return Yl(p)&&Ze(p,n)&&Nt.isTestStatusEnabled&&(h.skipped={}),n.urls&&(h["visited-urls-list"]=wS(p),h["visited-urls-json"]=vS(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 iu.Builder().buildObject(m)}catch(p){return ES(p)}}function ES(s){let e=new iu.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var iu,Ig,su,IS,ou=I(()=>{"use strict";iu=R(require("xml2js"));U();Ig=require("fs");ki();xo();su=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,i=await SS(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Ig.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)}};IS=su});var Rg={};q(Rg,{Reporter:()=>RS});function fs(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var au,cu,RS,xg=I(()=>{"use strict";W();au=A("team-city-reporter");cu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",i=`${e.name} (${e.testId})${r}`;return fs(i)}onTestStarted(e,t,r,i){if(r){au.debug("skip report test started because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testStarted name='${n}' captureStandardOutput='true' flowId='${i}']`)}onTestFailed(e,t,r,i,n,o){if(n){au.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(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){au.debug("skip report test finished because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testFinished name='${i}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let i=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${i}' message='${fs(r)}']`)}onTestPlanStarted(e,t,r,i){console.log(`##teamcity[testSuiteStarted name='${fs(i)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${fs(t)}']`)}},RS=cu});var Cg={};q(Cg,{Reporter:()=>xS});var lu,xS,Ag=I(()=>{"use strict";lu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,i,n){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:n}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},xS=lu});function Oo(s){let{platform:e}=process;e==="win32"?(0,ko.exec)(`start chrome ${s}`):e==="darwin"?(0,ko.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,ko.exec)(`google-chrome ${s}`)}var ko,uu=I(()=>{"use strict";ko=require("child_process")});var Pg={};q(Pg,{Reporter:()=>CS});var pu,CS,kg=I(()=>{"use strict";U();uu();pu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Oo(t)}},CS=pu});var du,Z,Mt=I(()=>{"use strict";Sg();du=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new Ao(e)),r===void 0||r.length===0){let{Reporter:i}=await Promise.resolve().then(()=>(ru(),tu));if(this.reporters.push(new i(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:n}=await Promise.resolve().then(()=>(ou(),nu));this.reporters.push(new n(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(xg(),Rg)),r.includes("console")&&Promise.resolve().then(()=>(ru(),tu)),r.includes("junit")&&Promise.resolve().then(()=>(ou(),nu)),r.includes("json")&&Promise.resolve().then(()=>(Ag(),Cg)),r.includes("chrome")&&Promise.resolve().then(()=>(kg(),Pg))])).forEach(n=>{n&&this.reporters.push(new n.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,i,n){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,i,n]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var n;let i=t==null?void 0:t(...r);for(let o of this.reporters)await((n=o[e])==null?void 0:n.call(o,...i||r))}}},Z=new du});async function mu(s,e,t){let r=gs[s];if(!r)return;let{slotId:i}=r;if(delete gs[s],!i){St.warn("failed to find slot slot id",{companyId:e,workerId:s});return}St.info("release slot id",{companyId:e,slotId:i});try{await gu(e,t,i)}catch(n){St.error("failed to release slot",{companyId:e,err:n})}}async function AS(s,e){let t=Object.values(gs).filter(Boolean);if(t.length!==0)try{await yu(s,e,t)}catch(r){St.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}function PS(s,e){Og=global.setInterval(()=>AS(s,e),1e4)}async function kS(s,e){let t=Object.keys(gs);if(t.length){St.warn("not all slots released before end runner flow",{companyId:s});try{await ne(t,r=>mu(Number(r),s,e))}catch(r){St.error("failed to release all slots",{err:r,companyId:s})}}}async function OS(s,e){await kS(s,e),clearInterval(Og)}async function Lg(s,e,t){let r;try{r=await fu(s,e)}catch(i){throw St.error("failed to get slot",{companyId:s,err:i}),new Error(bt.UNKNOWN)}if(St.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw St.error("invalid response - get slot",{res:r}),new Error(bt.UNKNOWN);if(r.status==="success")return _g(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new nt(bt.NOT_FOUND):r.code==="no-available-slot"?new rr("Failed to run test - concurrency limit reached"):(St.error("invalid code error response - get slot",{res:r}),new nt(bt.UNKNOWN))}async function Dg(s,e,t,r){let i=gs[r];if(!i)throw new Error("slot not found");Object.assign(i,t),_g(r,i),await hu(s,e,i),St.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var St,gs,Og,_g,_i,hs=I(()=>{"use strict";ye();W();U();oe();Q();St=A("slot-service"),gs={},Og=null,_g=(s,e)=>{gs[s]=e};_i={start:PS,end:OS}});function Mg(s,e=process){async function t(r){await ae(ne(Ng,async i=>i()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{r.message.includes("Command browsingContext")||(Di.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r))}),e.on("unhandledRejection",r=>{var i;if(Di.fatal("Caught unhandled promise rejection",r),!((i=r==null?void 0:r.message)!=null&&i.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Di.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",i=new Error(r);throw Di.error(r),t(i),i}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",i=new Error(r);throw Di.error(r),t(i),i}),e.once("exit",r=>{s(r)})}function ys(s){Ng.push(s)}var Di,Ng,Ni=I(()=>{"use strict";W();U();Di=A("process-handler"),Ng=[]});var jg={};q(jg,{installAllLazyDependencies:()=>NS,lazyRequire:()=>dt});async function dt(s,e={}){let t=xl(s);if(t)return t;let r;e.silent||(r=(0,Fg.default)(`Installing ${s} before first usage...`).start());try{let i=await DS(s);return r&&r.succeed(),i}catch(i){LS.warn("failed to install dependency lazily",{dependency:s,err:i});let n=Bg(s),o=`${s}@${n}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${o}`;throw r&&r.fail(l),i}}async function DS(s){return bs.has(s)||(bs.set(s,Ug(s)),bs.get(s).catch(()=>{bs.delete(s)})),bs.get(s)}async function Ug(s){let e=xl(s);if(e)return e;let t=Bg(s),r=`${s}@${t}`;return await ao(yt(),r),or(s)}async function NS(){let s=Object.keys(Cc);for(let e of s)await Ug(e)}function Bg(s){let e=Object.entries(Cc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Fg,LS,bs,Mi=I(()=>{"use strict";Fg=R(require("ora"));ls();W();U();kn();pi();LS=A("lazy-require"),bs=new Map});var $g,_o,Wg=I(()=>{"use strict";$g=require("istanbul-lib-report"),_o=class extends $g.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 Vg,Gg,Hg,Fi,Et,qg,Lo,bu,zg,MS,Kg,Jg,FS,US,Xg,BS,jS,$S,WS,VS,Yg,Qg=I(()=>{"use strict";Vg=R(require("ora")),Gg=R(require("dayjs")),Hg=R(require("test-exclude")),Fi=R(require("fs")),Et=R(require("path")),qg=R(require("istanbul-reports")),Lo=R(require("istanbul-lib-report"));ye();Q();U();W();Mi();Wg();bu=A("test-run-status"),zg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},MS=s=>!!zg(s).search,Kg=s=>s?zg(s).pathname.substring(1):"",Jg=(s,e)=>{let t=Kg(e);return!new Hg.default({relativePath:!1,include:s}).shouldInstrument(t)},FS=s=>s.substring(0,s.indexOf("?")),US=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await dt("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Xg=(s,e)=>`${Et.resolve(s,Kg(e))}.js`,BS=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ne(Object.values(t),async i=>{if(!i)return;let n=i.toObject();await ne(n.sources,async(o,a)=>{if(Jg(r,o))return;let c=Xg(e,o);await Fi.promises.mkdir(Et.parse(c).dir,{recursive:!0}),await Fi.promises.writeFile(c,n.sourcesContent[a])})})},jS={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(MS(e)&&(e=FS(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=Et.dirname(this.getPath(s));return Et.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},$S=async(s,e,t,r)=>{let{codeCoverageReporter:i}=s,n={},o=Lo.createContext({dir:t,coverageMap:e,watermarks:Lo.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Xg(r,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:jS}),qg.create(a,c).execute(o)}),n},WS=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:i}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await dt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Jg(i,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},VS=async(s,e)=>{let{mergeProcessCovs:r}=await dt("@bcoe/v8-coverage"),i={result:[]},n=new Map,a=(await wu(s,"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 Tu(d.sourceUrl)),n.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,i=r([i,{result:[d]}])})},{concurrency:20}),{covUrlMap:n,mergedCoverages:i}},Yg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;bu.info("start js coverage process");let i=(0,Vg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),n=Et.resolve(s.codeCoverageReportPath||"./coverage"),o=Et.resolve(n,`.js/${(0,Gg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?Et.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([dt("istanbul-lib-coverage"),VS(s.project,r)]);if(l.result.length===0){i.fail("Failed to report coverage information - js code coverage is empty");return}bu.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 US({sourceMapType:T,source:b,sourceMapDir:a});p[h]=v;let y=await WS(s,{source:b,sourceMap:v,functions:g});m.merge(y)}),await BS(s,o,p);let f=await $S(s,m,n,o);return i.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof C?i.fail(`${l}, missing arg: ${c.message}`):i.fail(l),bu.error(l,{err:c})}}});var Zg={};q(Zg,{SELENIUM_PERF_MARKS:()=>ke,SeleniumPerfStats:()=>kr});var ke,GS,kr,Ts=I(()=>{"use strict";U();ke={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},GS=["ALL",...Object.values(ke)],kr=class{constructor(){this.marks=Object.fromEntries(GS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=ce();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,Yn(r,50)],[`${t}_P95`,Yn(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var sh={};q(sh,{initServer:()=>zS,mapFilesToLocalDrive:()=>Su});function Su(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Do[t.id]?{screenshot:Do[t.id]}:{})),Object.keys(No).forEach(t=>{s.assets||={},s.assets[rh[t]]=No[t]}),s.assets||={},s.assets.screenshots=Object.values(Do)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function zS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await dt("multer"),i=typeof t=="string"?t:HS;await vu.promises.mkdir(i,{recursive:!0});let n=r({storage:r.diskStorage({async destination(c,l,d){let m=JSON.parse(c.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let p=Bi.join(i,m.testResultId);try{await vu.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,th.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&&qS.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(s,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 C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new C(`Port ${s} is already in use`));default:return l(p)}}})}var vu,eh,Bi,th,HS,Do,No,rh,qS,Eu=I(()=>{"use strict";vu=R(require("fs")),eh=R(require("os")),Bi=R(require("path")),th=R(require("express"));Q();Mi();HS=Bi.join(eh.tmpdir(),"testim/rca/"),Do={},No={},rh={"test-log":"consoleLogs","har-file":"networkLogs"},qS=Object.keys(rh)});var cr,Iu,ji,ih=I(()=>{"use strict";cr=R(require("lodash"));U();W();Iu=A("override-test-data-builder"),ji=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return cr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(e=!1){let{params:t,projectId:r}=this;return this.isObjectNotArray(t)&&t.overrideTestData!==void 0&&(this.isObjectNotArray(t.overrideTestData)&&!cr.isEmpty(t.overrideTestData)?(Object.keys(t.overrideTestData).forEach(i=>this.overrideSingleTest(i,t.overrideTestData[i])),delete t.overrideTestData):Iu.error("invalid overrideTestData",{overrideTestData:t.overrideTestData,projectId:r})),this.isObjectNotArray(t)&&t.overrideAllTestsData!==void 0&&(cr.isObject(t.overrideAllTestsData)&&!cr.isEmpty(t.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,t.overrideAllTestsData)),delete t.overrideAllTestsData):Iu.error("invalid overrideAllTestsData",{overrideAllTestsData:t.overrideAllTestsData,projectId:r})),this.isArrayOfObjects(t)&&e&&this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,t)),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}Iu.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return cr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(i=>{let n=r.map(d=>this.generateTestUniqId(d)),o=n.indexOf(i),a=n.lastIndexOf(i),c=r[o],l=this.createNewTestItems(c,t);return r.splice(o,a-o+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,i)=>{let n=ce();return{...e,resultId:n,testData:{value:r,index:i+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function $i(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw et.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var lr,et,KS,JS,XS,YS,Mo,nh=I(()=>{"use strict";lr=R(require("lodash"));U();oe();ps();hs();ye();Q();W();Mt();Ni();Qg();Ts();Eu();le();pe();ih();ki();et=A("test-run-status"),KS=Er(),JS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,XS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,YS=it();Mo=class{constructor(e,t,r,i){this.testInfoList=e;this.options=t;this.branchToUse=i;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.userTestDataParams={};this.seleniumPerfStats=new 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:KS,gitCommit:JS,gitRepoUrl:XS,runnerVersion:YS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:i,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:i,executionId:n,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:d,testStatus:m,testCreatorName:p,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:b,testSuites:T,allLabels:v}=a,y={originalTestResultId:t,previousTestResultId:r,config:lr.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},Cu({projectId:i,runId:n,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:y})}testStart(e,t,r,i){let n=this.getTestResult(r);return n.workerId=e,Z.onTestStarted(n,e,i,r),n}async updateTestStatusRunning(e,t,r){var l;let{project:i,remoteRunId:n,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await 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=lr.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:r})}async testStartReport(e,t,r){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,r),e}catch(o){throw et.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,i,n){let o=this.testStart(e,t,r,i);return this.testStartReport(o,t,n)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},et.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,i){let{name:n,testId:o,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Qe.EVALUATING&&Nt.isTestStatusEnabled){Z.onTestIgnored(e,r,`test in ${Qe.EVALUATING} status`);return}if(l){Z.onTestPassed(n);return}Z.onTestFailed(r,r.failureReason,ze(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,i,c)}calcResultText(e){return e.success?he.PASSED:he.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Z.onTestIgnored(e,r,`test in ${Qe.QUARANTINE}`)}monitorMemoryUsage(e){let t=yl();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,r,i,n){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=i,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&Su(o,et),o.resultUrl=ze(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,n),this.monitorMemoryUsage(o),Z.onTestFinished(o,e,n);let c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,r,i){var o;let n=r.exportsGlobal;try{try{await $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:r.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,r,i,n,o){let a=this.testEnd(e,t,r,i,n);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let i="",{APP_FROM_DEVICE:n,VIRTUAL_BUILD:o}=pl;return e&&(i=n),Zr(t,r)&&(i=o),i}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,i=(o=e.gridData)==null?void 0:o.type,n=t.map(a=>{var f,h,g,b;let c=e.browser?ai(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=es(O,i)&&oi(a.nativeApp)&&!e.appId,d=ir(e)&&(Zr(a.nativeApp,i)||l),m=Ze(a,e)||d,p={testId:a.testId,testOptimization:a.testOptimization,status:m?he.SKIPPED:he.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:r,testData:((f=a.testData)==null?void 0:f.value)||null,testDataPrioritized:((h=a.testData)==null?void 0:h.prioritize)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((g=a.testData)==null?void 0:g.total)||null,testDataIndex:((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,r){e==="redis"&&await _i.end(r,t),e==="mongo"&&await Ii.end(t)}async executionStart(e,t,r,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=r||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,lr.cloneDeep(this.testInfoList),t);this.testInfoList=S.overrideTestData(!0)}let h=await $i(o.beforeSuite,m),g=new ji(h,lr.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=lr.cloneDeep(this.testRunStatus);await ne(Object.keys(S),async B=>{var j;let G=S[B],E=(j=G.config)==null?void 0:j.testData,k=G.testId,L=await Uo(t,k,B,E,c.defaults);L&&(delete G.config.testData,G.config.testDataUrl=L)});let x=!!(o.useLocalChromeDriver||o.useChromeLauncher),_=xu({executionId:e,projectId:t,labels:i||[],startTime:r,executions:S,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:x,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){lr.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=Sl(this.testRunStatus),r=t.length,i=0,n=0,o=0;for(let{status:m,testStatus:p}of t)m===he.PASSED&&i++,m===he.SKIPPED&&n++,m===he.FAILED&&p===Qe.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await $i(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:i,skipped:n})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),et.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Yg(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Fo("FINISHED",e,this.options.project,r===i+n+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw et.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,i){let n=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await Ru(e,["QUEUED"],t,r,i,this.startTime,null,this.options.project);for(let o of n){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=i}return this.testRunStatus}}});function Au(s){var n;let e=s.canary?"-master.zip":".zip",t=`${Zt}/testim-headless${e}`,r=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(n=s.company)==null?void 0:n.companyId,projectId:s.project,runnerEnvironment:qs});return r||(QS.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),r=`${Zt}/testim-headless.zip`),!(s.ext||s.extensionPath)&&r&&(t=r,s.testimHeadlessExtensionDownloadUrl=r),{chrome:t,"edge-chromium":t}}function oh(s){let{chrome:e}=Au(s);return e}function Bo(s){let e=`${Zt}/sessionPlayer`;return s.canary?`${e}-master`:e}var QS,Wi=I(()=>{"use strict";le();pe();W();QS=A("runOptionsUtils")});function ws(s){var i;let t=(i=new RegExp(`^\\b(${Object.values(Pu).join("|")})`).exec(s))==null?void 0:i[0];return t||Pu[Xd]||"usw2"}var Pu,ch,jo=I(()=>{"use strict";le();Pu={"us-west-2":"usw2","eu-central-1":"euc1"},ch=Object.fromEntries(Object.entries(Pu).map(([s,e])=>[e,s]))});function lh(s,e){if(e){if(!iE.has(e)){Vi.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var uh,ph,Kt,dh,mh,fh,$o,gh,Vi,ZS,eE,Gi,tE,rE,sE,Jt,iE,Wo=I(()=>{"use strict";uh=R(require("ms")),ph=R(require("p-retry")),Kt=R(require("node:os")),dh=R(require("portfinder")),mh=R(require("node:child_process"));U();We();ye();fh=R(require("node:fs")),$o=R(require("node:fs/promises")),gh=require("node:path");Q();W();Wi();oe();pe();U();jo();Vi=A("lambdatestService"),ZS="https://downloads.lambdatest.com/tunnel/v3",eE={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=`${Kt.tmpdir()}/LT`,tE=`${Gi}/LT`,rE=(0,uh.default)("15m"),sE="2560x1440",Jt=class s{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===N.TESTIM_LAMBDATEST||e.type===N.LAMBDATEST||e.type===N.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t,r){s.isLambdatestGrid(e)&&(s.lambdatestConfigPromise||=ku(t,r),s.lambdatestConfig=await s.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?rE:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await Te(tE))return;let t=eE[Kt.platform()+Kt.arch()];if(!t)throw new Error(`tunnel on ${Kt.platform()+Kt.arch()} platform is not supported.`);let r=`${Gi}.zip`;await Xe(`${ZS}/${t}`,r),await Ye(r,Gi)}static async chmodLtTunnel(e){if(!(Kt.platform()==="win32"||!await Te(e))){try{await $o.access(e,fh.constants.X_OK);return}catch{}try{await $o.chmod(e,"777")}catch(r){throw Vi.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ie(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){s.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await dh.getPortPromise(),{gridData:r={},gridUsername:i,gridPassword:n,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;s.tunnelName=ce();let l=["--tunnelName",s.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,...gl(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,api.coralogix.com,*.betterstackdata.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(i&&n)l=[...l,"--user",i,"--key",n];else throw new C("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 C("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await s.delay(3e3),await s.chmodLtTunnel((0,gh.join)(Gi,"LT")),s.tunnel=mh.spawn("./LT",l,{cwd:Gi});let d="",m="";s.tunnel.stdout.on("data",p=>{d+=p.toString()}),s.tunnel.stderr.on("data",p=>{m+=p.toString()});try{let p=await(0,ph.default)(()=>ve(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});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||!s.tunnel))return new Promise((t,r)=>{s.tunnel.on("close",i=>{i&&r(new Error(`tunnel process exited with code ${i}`)),t()}),s.tunnel.kill()})}getCapabilities(e,t,r,i,n,o,a,c){var x;if(!this.isActive)return{};let l=s.lambdatestConfig.CAPABILITIES[t]||{},d={...s.tunnelName&&{tunnel:!0,tunnelName:s.tunnelName}},m=[],{canary:p,ext:f,extensionPath:h,installCustomExtension:g}=e,b={platform:lh(i,a==null?void 0:a.os)||lh(i,(x=o==null?void 0:o.lt)==null?void 0:x.platform)||l.platform||s.lambdatestConfig.PLATFORM,resolution:s.lambdatestConfig.RESOLUTION??sE,...t!=="safari"&&{version:l.version}};if(c!==J.APPIUM&&c!==J.SELENIUM&&!f){let _=Au({canary:p});!h&&_[t]&&(m=[...m,_[t]]),h&&De(h)&&(m=[...m,h]),m.length||Vi.warn("No extension was loaded in LambdaTestService",{extUrls:_,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}:{};return{"LT:Options":{build:r,name:`${i} - ${n}`,...w,selenium_version:s.lambdatestConfig.SELENIUM_VERSION,timezone:s.lambdatestConfig.TIMEZONE,...l,...b,loadExtension:m,...d,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}},iE=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 hh,nE,Vo,Ou=I(()=>{"use strict";Q();hh=["platformName","platform","app","bundleId","appPackage","extensions"],nE=["selenium_version","protocol","host","port","path","build"],Vo=(s,e)=>{let t=e==="lambdaTest"?[...hh,...nE]:hh,r=[],i=[s];for(;i.length;){let n=i.pop();for(let[o,a]of Object.entries(n))t.includes(o)&&r.push(o),a&&typeof a=="object"&&i.push(a)}if(r.length)throw new C(`Custom capabilities contains forbidden keys: ${r.join(", ")}`)}});function aE(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Ch(s){return Sh.readFileSync(s,{encoding:"base64"})}function Ah(s,e,t,r){if(t!=null&&t.isLambdatestRun()&&De(s))return null;if(s){if(r)return s.endsWith(".zip")?(Ye(s,Th),Th):s;let i=Ch(s);Ss.info(`adding extension: custom, path: ${s} length: ${i.length} hash: ${Du(i)} current extension count: ${e.length}`),e.push(i)}return null}function Ph(s,e,t,r,i,n){if(i!=null&&i.isLambdatestRun())return null;let o=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!o){let m=typeof s.ext=="string"?s.ext:`${__dirname}/..`,p=r||m,f=`--load-extension=${p}`;return Ss.info(`adding extension: testim unpacked , path: ${p}`),t.push(f),null}let c=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&o&&(c=_r.basename(o));let l=_r.join(process.cwd(),c);if(n)return Ye(l,bh),bh;let d=Ch(l);return Ss.info(`adding extension: testim zipped, path: ${l} length: ${d.length} hash: ${Du(d)} current extension count: ${e.length}`),e.push(d),null}function cE(s,e,t,r,i,n,o,a){var g,b;let c=t.seleniumName||t.browserValue,l=[],d=[...Rh];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":_u.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":_u.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(Lu(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",s.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}Lu(i)&&c==="MicrosoftEdge"&&(s.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"]=_u.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(s.desiredCapabilities,{browserName:c});function p(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+ll.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}p(),Ah(r,l,o),a===J.EXTENSION&&Ph(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 Jt.isLambdatestGrid(i)&&delete m.w3c,e.oldCapabilities&&i.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||i.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function uE(s,e,t){let r={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":wh.join(","),"browser.helperApps.neverAsk.openFile":wh.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{"LT:Options":{enableCustomTranslation:!0}}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function vs(s){return`${s.width}x${s.height}`}function hE(s){let{platform:e}=s;if(!e)return vs(vh);let t=e.split(" ")[1];return e.startsWith("Windows")&&gE.has(t)?vs(dE):e==="Linux"?vs(pE):e.startsWith("macOS")?vs(mE):vs(e==="OS X El Capitan"||e==="OS X Yosemite"?fE:vh)}function yE(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let i={"sauce:options":{name:e}};if(i["sauce:options"].screenResolution=hE(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version;let n=r.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,Ih.cloneDeep)(t.sl),o);return Ve.merge(a,i,r)}return Ve.merge(i,r)}return{}}function bE(s){let{runnerOptions:e}=s;if(Ve.isEmpty(e.browserstack))return{"bstack:options":{}};let{projectData:t,testRunConfig:r,testId:i,testName:n,executionId:o,executionName:a}=s,c={"bstack:options":{buildName:`${a} - ${o}`,sessionName:`${n} - ${i}`,projectName:`${t.name} - ${t.projectId}`,...e.browserstack}};return r&&r.browserValue==="safari"&&r.bs.safari_version&&(c["bstack:options"].os_version=r.bs.safari_version,r.bs.safari_version==="10"&&Object.assign(c["bstack:options"],{"safari.options":{technologyPreview:!0}})),c}function TE(s){return s.perfecto?s.perfecto:{}}function wE(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function vE(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:i}=s,n=r||t.user||e.user,o=i||t.key||e.key,a={};return n&&o&&(a.Authorization=Ic(n,o)),a}function Go(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function Ho(s){var B,G,E,k;let{overrideConfiguration:e,browserOptions:t,testId:r,testName:i,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:d,testResultId:m,lambdatestService:p,mode:f,customCapabilities:h,useLocalChromeDriver:g}=s;if(o.mode==="local"){let L=[],j=[...Rh],V={};t.headless&&j.push("--headless"),t.silentDebuggerExtensionApi&&j.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&j.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let re=Go();re.length&&re.forEach(ge=>j.push(`--disable-features=${ge}`))}catch{}t.chromeExtraArgs&&t.chromeExtraArgs.forEach(re=>j.push(`--${re}`)),t.chromeBinaryLocation&&(V.binary=t.chromeBinaryLocation);let K,z=null;return f!==J.SELENIUM&&(K=Ph(t,L,j,null,p,g)),z=Ah(a,L,p,g),g&&j.push("--enable-unsafe-extension-debugging","--remote-debugging-pipe"),{logLevel:yh,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:j,extensions:L,...V},browserName:"chrome",...g&&{webSocketUrl:!0}},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515,...g&&K&&{unzippedTestimExtensionPath:K},...g&&z&&{unzippedCustomExtensionPath:z}}}let{driverRequestTimeout:b,driverRequestRetries:T}=t,v=vE(t,o),y={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:yh,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(Lu(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),x={runnerOptions:t,testId:r,testName:i,testRunConfig:n,executionId:c,executionName:l,projectData:d};Ve.merge(y.desiredCapabilities,yE(t,i,n),bE(x),TE(t),wE(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=lE(y,t,n,a,o,_,p,f);break;case"firefox":y=uE(y,t,p);break;case"safari":case"safari technology preview":y=aE(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=re=>re[o.provider]||re[y.host]||re[L[y.host]],V=re=>{var ge,qe;return j(re)||re[(ge=y.desiredCapabilities)==null?void 0:ge.browserName]||re[(qe=y.desiredCapabilities)==null?void 0:qe.version]||re||{}},K=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),z=V(V(K));Object.keys(z).length&&(Ss.info(`Adding custom capabilities: ${JSON.stringify(z)}`),Object.assign(y.desiredCapabilities,z))}catch(L){Ss.error("Failed to load custom capabilities",{error:L,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(y.desiredCapabilities&&!y.capabilities&&(oE(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,s.printFinalCaps){let L=(G=y.capabilities)==null?void 0:G.alwaysMatch,j=JSON.parse(JSON.stringify(y)),V=(E=j==null?void 0:j.capabilities)==null?void 0:E.alwaysMatch,K=re=>re.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(re=>{var ge,qe;V!=null&&V[re]&&(V[re].extensions=(qe=(ge=L==null?void 0:L[re])==null?void 0:ge.extensions)==null?void 0:qe.map(K))}),V!=null&&V.loadExtension&&(V.loadExtension=(k=L==null?void 0:L.loadExtension)==null?void 0:k.map(K));let z=require("node:util");console.log(z.inspect(j,{showHidden:!1,depth:null,colors:!0}))}return y}var Sh,_r,Eh,Ve,Ih,Ss,yh,_u,Rh,xh,bh,Th,Du,Lu,oE,lE,wh,vh,pE,dE,mE,fE,gE,qo=I(()=>{"use strict";Sh=R(require("node:fs")),_r=R(require("node:path")),Eh=R(require("node:crypto")),Ve=R(require("lodash"));U();le();W();al();U();pe();oe();Wo();Ou();Ih=require("lodash"),Ss=A("testim-desired-capabilities-builder"),yh=_n?"debug":"silent",_u={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Rh=["--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"],xh=_r.join(Tt,"extensions"),bh=_r.join(xh,"testim-headless"),Th=_r.join(xh,"custom-extension"),Du=(...s)=>Eh.createHash("sha256").update(s.join("")).digest("hex"),Lu=s=>s.type===N.DEVICE_FARM||s.type===N.HYBRID&&s.provider==="devicefarm",oE=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=O.flags.unsupportedCapsFields.getValue();let i=JSON.parse(t);if(!Array.isArray(i))return;i.forEach(n=>{delete e[n]})}catch{Ss.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};lE=Ve.memoize(cE,(s,e,t,r,i,n)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(Ve.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(i.type);return Du(o,a,c,r,l,n)}),wh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];vh={width:1920,height:1080},pE={width:1920,height:1200},dE={width:2560,height:1600},mE={width:2360,height:1770},fE={width:2048,height:1536},gE=new Set(["7","8","8.1","10","11"])});function Ft(s){var e,t,r,i,n,o,a,c;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||((t=s.message)==null?void 0:t.toLowerCase())==="unknown error"||((r=s.message)==null?void 0:r.match(/Unknown timeout type/))||s.name==="unknown command"||((i=s.message)==null?void 0:i.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=s.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((c=s.message)==null?void 0:c.match(/\.\w* is not a function/))}function Oh(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var Nu=I(()=>{"use strict"});function Mu(s){function e(p){return p?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(p.nodeType):!1}function t(p){return p?r(p.parentNode,e):null}function r(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(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Mu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(n(s,"visibility")!=="visible")return!1;let d=!!i(s,p=>Number(n(p,"opacity"))===0),m=!!i(s,p=>n(p,"display")==="none");return!(d||m||!o(s)||c(s))}var _h=I(()=>{"use strict"});var Lh,Dh,Ut,SE,EE,zo,Nh=I(()=>{"use strict";Lh=R(require("promise-queue")),Dh=R(require("webdriverio"));le();je();U();W();Gr();_h();Nu();Ts();Ut=A("WebDriverApi"),SE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},EE={implicit:0,pageLoad:1,script:2},zo=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}rejectWithLog(e,t){let{testName:r,testResultId:i}=this,n=t?t.toString().slice(0,2e3):"";throw Ut.warn("error from selenium",{err:e,testResultId:i,testName:r,crashingFunc:n}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Ac!==void 0&&(e=Ac);let t=1/0;this.queue=new Lh.default(e,t)}async addToQueue(e){var r,i;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(n){return this.rejectWithLog(n,e)}finally{(i=this.seleniumPerfStats)==null||i.markEnd(t)}}async installExtensions(e){var r;let t=[e==null?void 0:e.unzippedTestimExtensionPath,e==null?void 0:e.unzippedCustomExtensionPath].filter(Boolean);for(let i of t)await((r=this.client)==null?void 0:r.send({method:"webExtension.install",params:{extensionData:{type:"path",path:i}}}))}async initClient(e,t,r,i,n){var c,l,d,m,p,f,h,g;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let o=((c=e.capabilities.alwaysMatch)==null?void 0:c.loadExtension)||((l=e.capabilities.alwaysMatch)==null?void 0:l.loadExt)||((f=(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:r,testName:t,extUrl:o}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await Dh.remote(e),this.client.on("dialog",async b=>{try{await b.accept()}catch{}}),i&&await this.installExtensions(n),this.logGridStatus(r)}),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,r="N/A",i="N/A",n;try{n=await this.client.status();for(let a of n.nodes||[])for(let c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){r=a,i=c;break}}catch(a){if(a.message==="unknown error"){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}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ut.info("grid status",{gridStatusMsg:n.message,ready:n.ready,browserNode:r,gridSlot:i,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let i=a=>{throw Object.assign(a,{executedScript:e}),a},n=()=>this.client.execute(e,t).catch(i),o=()=>this.client.executeScript(e,t).catch(i);if(this.unsupportedActions.has("execute"))return n();t=t.map(a=>{if(a===null){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 r=await((i=this.client)==null?void 0:i.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(ke.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,ke.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(ke.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Ue(e)))}finally{this.seleniumPerfStats.markEnd(t,ke.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(async()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(i=>({value:i})),r=()=>this.execute(Mu,{ELEMENT:e,[Qt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(i){if(Ft(i))return this.unsupportedActions.add("elementIdDisplayed"),r();throw i}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Oh(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 r=()=>{let n=[];return n[EE[e]]=t,this.client.setTimeouts(...n)},i=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return i();try{return await r()}catch(n){if(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 r=function(i,n){window.scrollTo(i,n)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Ue(e)),await this.elementIdValue(Ue(e),t)}async getViewportSize(e){let t=await this.execute(SE);if(typeof e=="string"&&/(width|height)/.test(e)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitFormManually(e){return this.addToQueue(async()=>{var n;let t=(n=this.client)==null?void 0:n.$(e),r=t.$('button[type="submit"]');return await r.isExisting()?r.click():t.$("input:last-of-type").keys("Enter")})}async findElementAndPress(e,t,r){let 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:r})})}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:r})});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 r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).dragAndDrop(t)})}}moveTo(e,t,r){let i={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(i,"yoffset")&&(i.yOffset=1),this.isSafari()&&!Object.hasOwn(i,"xoffset")&&(i.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let n=this.client.$(e);await this.client.action("pointer").move({origin:n}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),n=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,n)}try{return await r()}catch(i){throw i}})}}setCookie(e,t,r,i,n,o,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:i,secure:n,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).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,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.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 r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return 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 ur={};q(ur,{getSessionPlayer:()=>ee,options:()=>Uu});var Ko,Uu,Fu,ee,Se=I(()=>{"use strict";Ko=require("path");W();Uu={playerPath:void 0},ee=()=>{if(Fu)return Fu;let s=(je(),Me(Be));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(gi(),Me(fi)),t=e(),r=Uu.playerPath?(0,Ko.resolve)(Uu.playerPath,"src/background/sessionPlayerInit.ts"):(0,Ko.join)(t,"sessionPlayer.js"),i=require(r);return s.log("getSessionPlayerRequire end"),Fu=i,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&i.setLoggerFormatter&&i.setLoggerFormatter(Dm),i}});var Mh={};q(Mh,{doubleClick:()=>IE});var IE,Fh=I(()=>{"use strict";IE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let i=s.events,n={status:"done",success:!0};window.__unloadNavigator=function(){e(n)};let o=function(p){function f(v,y,w){return w>v&&w<y}let h=p.pointerPosition||{},g=r.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=>r.dispatchEvent(f));let p=d();dispatchFocus(s.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={};q(Hi,{dispatchFocus:()=>RE});function RE(s,e){function t(n){let o=document.createEvent("HTMLEvents");return o.initEvent(n,!0,!1),o}function r(){var o;let n=document.activeElement;for(;(o=n.shadowRoot)!=null&&o.activeElement;)n=n.shadowRoot.activeElement;return n}function i(n,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),n.dispatchEvent(t("focusin")),n.dispatchEvent(t("focus")),typeof n.focus=="function"&&n.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let n=getLocatedElement(s);if(n&&n!==e)try{i(n,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var qi=I(()=>{"use strict"});var Wh={};q(Wh,{WebDriver:()=>Dr});async function PE(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await CE(r):void 0}catch(r){Ge.info("Error getting cdpAddress",r);return}}var Is,jh,$h,Ge,Es,xE,Uh,CE,Lr,AE,Bh,zi,Dr,Ki=I(()=>{"use strict";Is=R(require("lodash"));U();je();qo();jh=R(require("p-retry")),$h=R(require("ua-parser-js"));Gr();W();Nu();Nh();Q();pe();Ts();Ge=A("webdriver"),[Es,xE]=[0,2],{extractElementId:Uh,getCdpAddressForHost:CE}=Y,Lr=()=>(Se(),Me(ur)).getSessionPlayer().codeSnippets,AE=()=>(Se(),Me(ur)).getSessionPlayer().locatorBuilderUtils,Bh=()=>(Se(),Me(ur)).getSessionPlayer().utils,zi=()=>(Se(),Me(ur)).getSessionPlayer().positionUtils;Dr=class extends zo{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.keepAliveFailedCallbacks=[];this.generalKeepAliveFailures=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null)}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}registerToKeepAliveFailed(t){this.keepAliveFailedCallbacks.push(t)}unregisterToKeepAliveFailed(t){this.keepAliveFailedCallbacks=this.keepAliveFailedCallbacks.filter(r=>r!==t)}async init(t){var B,G,E,k,L,j,V,K;let{projectData:r,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=!!((E=(G=(B=n==null?void 0:n.company)==null?void 0:B.activePlan)==null?void 0:G.premiumFeatures)!=null&&E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let S=Ho({projectData:r,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 x=g?0:1500,_=g?(()=>null):()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let z={unzippedTestimExtensionPath:S.unzippedTestimExtensionPath,unzippedCustomExtensionPath:S.unzippedCustomExtensionPath},re=await this.initClient(S,a,f,w,z);M("after initResult before getCdpAddress in init"),this.cdpUrl=await PE(re),M("after getCdpAddress in webdriver.js init"),Ge.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await ie(x),O.flags.dontFocusOnInit.isEnabled()||await _(),M("after focus and delay in webdriver.js init")}catch(z){let re=JSON.stringify(Is.omit(S,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Ge.error("failed to init webdriver",{err:z,capabilitiesAsString:re});let ge=((L=(k=n==null?void 0:n.company)==null?void 0:k.activePlan)==null?void 0:L.plan)==="free";throw(j=z.stack)!=null&&j.includes("at startWebDriverSession")&&((V=z.message)!=null&&V.startsWith("Failed to create session"))&&((K=z.message)!=null&&K.includes("Timeout awaiting 'request'"))&&ge?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(z.message)?new zr(z.message):/capabilit(y|ies)/.test(z.message)&&!/UND_ERR_HEADERS_TIMEOUT/.test(z.message)?new Bn(z.message):/403 Forbidden/.test(z.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(z.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${z.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)),r=this._keepAliveRequests.map(({start:n})=>n).filter(Boolean),i=t(r).map(([n,o])=>o-n);return Math.max(...i)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(i=>t.message.includes(i))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),i=(a,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function n(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=ce();r(o);try{await this.executeJS(n),this._isAlive=!0,i("end",o),this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0}catch(a){if(i("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,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,r){t.forEach(i=>{try{i(r)}catch{}})}async switchToLocatedFrame(t){let r=await this.getElement(t);if(!r.value)throw new Error("Element not found");let i=Uh(r.value);return await this.switchFrame({ELEMENT:i,[Qt]:i}),r}switchFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new jn:r}}async getElement(t){var n;let r=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(r,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(`
|
|
20
|
+
var fn = ${Lr().getLocatedElementCode};
|
|
21
21
|
return fn.apply(null, arguments);
|
|
22
|
-
`,t)}finally{this.seleniumPerfStats.markEnd(
|
|
23
|
-
var getLocatedElement = ${
|
|
24
|
-
var setDynamicParentAttribute = ${
|
|
22
|
+
`,t)}finally{this.seleniumPerfStats.markEnd(r,ke.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,ke.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...i){return await this.timeouts("script",r),await this.executeAsync(t,...i)}async markDynamicParent(t,r){function i({attributeName:n,attributeValue:o,locatedElement:a}){let c=getLocatedElement(a);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(n,o)}await this.executeJS(`
|
|
23
|
+
var getLocatedElement = ${Lr().getLocatedElementCode};
|
|
24
|
+
var setDynamicParentAttribute = ${i.toString()};
|
|
25
25
|
return setDynamicParentAttribute.apply(null, arguments)
|
|
26
|
-
`,{attributeName:
|
|
27
|
-
const getLocatedElement = ${
|
|
28
|
-
const getLocation = ${
|
|
26
|
+
`,{attributeName:AE().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(i){let n=getLocatedElement(i);if(!n)return null;let o=parseInt(window.getComputedStyle(n).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(n).paddingLeft.replace("px",""),10)||0,c=n.getBoundingClientRect();return{top:Math.round(c.top+o),left:Math.round(c.left+a)}}return this.executeJS(`
|
|
27
|
+
const getLocatedElement = ${Lr().getLocatedElementCode};
|
|
28
|
+
const getLocation = ${r.toString()};
|
|
29
29
|
return getLocation.apply(null, arguments)
|
|
30
|
-
`,t)}getElementLocationWithPadding(t){return this.getLocatedElementRectWithPadding(t)}getLocatedElementRect(t){function
|
|
31
|
-
const getLocatedElement = ${
|
|
32
|
-
const getLocation = ${
|
|
30
|
+
`,t)}getElementLocationWithPadding(t){return this.getLocatedElementRectWithPadding(t)}getLocatedElementRect(t){function r(i){let n=getLocatedElement(i);if(!n)return null;let o=n.getBoundingClientRect();return{bottom:Math.round(o.bottom),height:Math.round(o.height),x:Math.round(o.left),right:Math.round(o.right),y:Math.round(o.top),width:Math.round(o.width)}}return this.executeJS(`
|
|
31
|
+
const getLocatedElement = ${Lr().getLocatedElementCode};
|
|
32
|
+
const getLocation = ${r.toString()};
|
|
33
33
|
return getLocation.apply(null, arguments)
|
|
34
|
-
`,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function
|
|
35
|
-
const getLocatedElement = ${
|
|
36
|
-
const extractText = ${
|
|
34
|
+
`,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function r(n,o){function a(p){var h;return(h=p.childNodes)!=null&&h.length&&[...p.childNodes].filter(g=>g.nodeType===Node.ELEMENT_NODE).forEach(g=>{typeof g.tagName=="string"&&g.tagName.toLowerCase()==="title"?p.removeChild(g):a(g)}),p}function c(p){return["INPUT","TEXTAREA"].includes(p.tagName)}function l(p){var f,h,g;try{if(p.shadowRoot&&!((g=(h=Object.getOwnPropertyDescriptor((f=p.ownerDocument.defaultView)==null?void 0:f.Node.prototype,"textContent"))==null?void 0:h.get)!=null&&g.toString().includes("[native code]")))return p.shadowRoot.textContent.replace(/(\r\n|\n|\r)/gm,"")}catch{}if(o&&Array.prototype.some.call(p.children,b=>b.hidden)){let b=p.cloneNode(!0);return Array.prototype.filter.call(b.children,v=>v.hidden).forEach(v=>b.removeChild(v)),b.textContent.replace(/(\r\n|\n|\r)/gm,"")}return p.textContent.replace(/(\r\n|\n|\r)/gm,"")}function d(p){if(c(p))return p.value;if(p instanceof SVGElement){let f=p.cloneNode(!0);return a(f).textContent.replace(/(\r\n|\n|\r)/gm,"")}return l(p)}let m=getLocatedElement(n);return m?d(m):""}let{value:i}=await this.executeJS(`
|
|
35
|
+
const getLocatedElement = ${Lr().getLocatedElementCode};
|
|
36
|
+
const extractText = ${r.toString()};
|
|
37
37
|
return extractText.apply(null, arguments)
|
|
38
|
-
`,t,this.ignoreHiddenTagsText);return
|
|
39
|
-
var getLocatedElement = ${
|
|
40
|
-
var dispatchFocus = ${
|
|
41
|
-
var doubleClick = ${
|
|
38
|
+
`,t,this.ignoreHiddenTagsText);return i}async getHTML(t){var n,o;let r=Lr().getHtmlCode(void 0,t),i=this.seleniumPerfStats.markStart(ke.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(i,ke.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(i,ke.GET_HTML);let c=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(o=(n=this.client)==null?void 0:n.requestHandler)!=null&&o.sessionID||Object.assign(c,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),c}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class n extends Error{}function o(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,jh.default)(async()=>{let{value:l}=await this.windowHandleSize(),{value:d}=await this.execute(o),m=l.width-d.screenWidth,p=l.height-d.screenHeight;await this.windowHandleSize({width:t.width+m,height:t.height+p});let{value:f}=await this.execute(o);if(f.screenWidth!==t.width||f.screenHeight!==t.height)throw new n},{retries:4,factor:1,minTimeout:0}).catch(l=>{if(!(l instanceof n))throw l});if(typeof t!="object"||typeof t.width!="number"||typeof t.height!="number"||r!==void 0&&typeof r!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(r===void 0?!0:r)?a():this.windowHandleSize(t)}setViewportSize(t,r){return this.setViewportSizeNEW({width:t,height:r},!0)}getBrowserMajorVersion(t){var r;try{return parseInt(((r=t.browser)==null?void 0:r.version)||"0",10)}catch(i){return Ge.error("failed to get browser version",{err:i}),0}}async getBrowserAndOS(){function t(a){let c=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(c[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(c[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";c=c[2]?[c[1],c[2]]:[a.appName,a.appVersion,"-?"];let l=a.match(/version\/(\d+)/i);return l!==null&&c.splice(1,1,l[1]),c[0].toLowerCase()}if(this.browserAndOS)return this.browserAndOS;function r(){var a;return(a=window==null?void 0:window.navigator)!=null&&a.userAgent?window.navigator.userAgent:"unknown"}let{value:i}=await this.executeJS(r),n=(0,$h.default)(i),o=n.os;return this.browserAndOS={os:`${o.name} ${o.version}`,browserMajor:this.getBrowserMajorVersion(n),browser:t(i),userAgent:i,browserVersion:n.browser.version},this.browserAndOS}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:i,clickOffset:n}=t,o=zi().calculateElementMiddlePoint(i),a=n.x,c=n.y;return!Bh().isWithinBounds(i.left,i.left+i.width,o.x+a)||!Bh().isWithinBounds(i.top,i.top+i.height,o.y+c)?(Ge.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,c,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:i,clickOffset:n}=t,o=i.left+n.x+r.x,a=i.top+n.y+r.y;return{x:o,y:a}}async actWithActionsAPI(t,r,i,n){let o=this.getRelativeMoveActions(t,i),a=this.getClickActions(n,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(a)}])}catch(c){Ge.error("tried to use element origin but failed because of visibility, trying absolute",c);let{x:l,y:d}=this.computeAbsoluteMovement(t),m=this.getMoveActions(l,d);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:m.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,Es,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:i}]=await Promise.all([Promise.resolve().then(()=>(Fh(),Mh)),Promise.resolve().then(()=>(qi(),Hi))]);return this.executeCodeAsync(`
|
|
39
|
+
var getLocatedElement = ${Lr().getLocatedElementCode};
|
|
40
|
+
var dispatchFocus = ${i.toString()};
|
|
41
|
+
var doubleClick = ${r.toString()};
|
|
42
42
|
var eventData = arguments[0];
|
|
43
43
|
var done = arguments[1];
|
|
44
44
|
return doubleClick.call(null, eventData, done);
|
|
45
|
-
`,t.timeout,t)}getClickActions(t=[],
|
|
46
|
-
var res = requireOrImportMethod('${
|
|
45
|
+
`,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(i=>({type:i,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,Es,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,xE,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(i){if(Ft(i))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw i}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(i){if(Ft(i))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw i}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:i,y:n}=r.clickOffset;try{return await this.moveTo(t,i,n)}catch(o){if(Ft(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,i="viewport",n=0){return[{type:"pointerMove",duration:n,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:i}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(i){Ge.error("tried to use element origin but failed because of visibility, trying location",i);let n=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(n)}}getMoveRelativeSequence(t,r,i,n){let o=(p,f)=>Math.hypot(p.x-f.x,p.y-f.y),a={x:t,y:r},c={x:i,y:n},d=Math.round(o(a,c)/10),m=Array.from({length:d},()=>({x:Math.round((c.x-a.x)/d),y:Math.round((c.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,i,n){return this.getMoveRelativeSequence(t,r,i,n).reduce((a,c)=>{let l=a.at(-1);return a.concat({x:Math.round(l.x+c.x),y:Math.round(l.y+c.y)})},[{x:Math.round(t),y:Math.round(r)}])}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:i,fromY:n,toRect:o,toX:a,toY:c}=t,l=zi().calculateElementMiddlePoint(r),d=zi().calculateElementMiddlePoint(o),m=Math.floor(l.x+i),p=Math.floor(l.y+n),f=Math.floor(d.x+a),h=Math.floor(d.y+c),g=this.getMoveAbsoluteSequence(m,p,f,h),b=this.getMoveActions(m,p),T=this.getClickActions(["pointerDown"],Es),v=Is.flatMap(g,x=>this.getMoveActions(x.x,x.y)),y=this.getMoveActions(f,h),w=this.getClickActions(["pointerUp"],Es),S=b.concat(T).concat(v).concat(y).concat(w);return this.actions([{type:"pointer",id:"mouse",actions:S}])}async dragAndDrop(t){return this.isSafari()?this.dragAndDropWithActionsAPIWithGeneratedMoves(t):this.dragAndDropWithActionsAPI(t)}doubleClickFallback(t,r,i){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,i)}async doubleClick(t,r,i){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,i);try{return await this.doDoubleClick(t)}catch(n){if(Ft(n))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,i);throw n}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:i,fromY:n,toRect:o,toX:a,toY:c}=t,l=zi().calculateElementMiddlePoint(r),d=zi().calculateElementMiddlePoint(o),m=Math.floor(l.x+i),p=Math.floor(l.y+n),f=Math.floor(d.x+a),h=Math.floor(d.y+c);await this.moveWithActionsAPI({x:m,y:p});let g=this.getClickActionList(["pointerDown"],Es);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let b=this.getClickActionList(["pointerUp"],Es);return this.actions(b)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(Uh(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},i;try{i=await this.getElementLocation(t)}catch(n){Ge.error("error getting element location",{err:n})}return i!=null&&i.value?{top:i.value.y,left:i.value.x,width:i.value.width,height:i.value.height}:r}async end(){Ge.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Ge.warn("failed to close session because session is undefined"),this.stopKeepAliveInterval();try{return await super.end()}catch{return}}async submit(t){return super.submitFormManually(t)}}});var Bu,ju,Ji,$u=I(()=>{"use strict";W();pe();ye();Bu=A("lab-features-service"),ju=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(Bu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),i=r?await Wu(e):[];this.featuresForProject=i,this.labBatman=r}catch(r){Bu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=O.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:i,labBatman:n}=this,o=i.find(c=>c.featureFlagName===e),a=o==null?void 0:o.enabled;return!!(n&&a)}isLabsEnabledForCompany(e){var t;return!!((t=e==null?void 0:e.premiumFeatures)!=null&&t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw Bu.error(t,{featureFlagName:e.name}),new Error(t)}},Ji=new ju});function kE(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function OE(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:r}=globalThis.require("path"),{promises:i}=globalThis.require("fs");return{sync:!1,lib:i.readFile(`${s}${t}package.json`).then(o=>{let a=JSON.parse(o);return import(r(s,a.main||`${t}index.js`))})}}}function _E(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function LE(s,e,t,r,i={},n=void 0,o=void 0){let a=Object.keys(i).map(h=>`
|
|
46
|
+
var res = requireOrImportMethod('${kE(i[h])}');
|
|
47
47
|
if (res.sync) {
|
|
48
48
|
var ${h} = res.lib;
|
|
49
49
|
} else {
|
|
50
50
|
var ${h} = await res.lib;
|
|
51
51
|
}
|
|
52
52
|
`).join(""),c=o?`
|
|
53
|
-
${
|
|
53
|
+
${Hh.default.toString()}
|
|
54
54
|
var fileBuffer = dataUriToBuffer('${o}');
|
|
55
55
|
`:"var fileBuffer = null;",l=`
|
|
56
56
|
const getMessage = arguments => {
|
|
@@ -106,7 +106,7 @@ Testim had missing write access to ${s||e}
|
|
|
106
106
|
});
|
|
107
107
|
`,d=`
|
|
108
108
|
function injectCode(params, args, incomingParams, context, code) {
|
|
109
|
-
const constructWithArguments = ${
|
|
109
|
+
const constructWithArguments = ${_E.toString()}
|
|
110
110
|
|
|
111
111
|
const resolve = result => {
|
|
112
112
|
parentPort.postMessage({
|
|
@@ -172,7 +172,7 @@ Testim had missing write access to ${s||e}
|
|
|
172
172
|
// A hack to fix an issue with stringified functions which use require. when compiling to JS, calls to require change to __require.
|
|
173
173
|
const __require = require;
|
|
174
174
|
const { parentPort } = require('worker_threads');
|
|
175
|
-
const requireOrImportMethod = ${
|
|
175
|
+
const requireOrImportMethod = ${OE.toString()}
|
|
176
176
|
|
|
177
177
|
// requireCode will set async to be true if needed.
|
|
178
178
|
${a}
|
|
@@ -181,7 +181,7 @@ Testim had missing write access to ${s||e}
|
|
|
181
181
|
|
|
182
182
|
${l}
|
|
183
183
|
|
|
184
|
-
const isPromise = ${
|
|
184
|
+
const isPromise = ${Hc.toString()}
|
|
185
185
|
|
|
186
186
|
parentPort.once('message', input => {
|
|
187
187
|
const { incomingParams, context, code } = input;
|
|
@@ -192,12 +192,12 @@ Testim had missing write access to ${s||e}
|
|
|
192
192
|
|
|
193
193
|
const params = ["context"]
|
|
194
194
|
.concat(incomingParams.as.functionParameters)
|
|
195
|
-
.concat(${JSON.stringify(Object.keys(
|
|
195
|
+
.concat(${JSON.stringify(Object.keys(i))})
|
|
196
196
|
.concat(['exports', 'exportsTest', 'exportsGlobal']);
|
|
197
197
|
|
|
198
198
|
const args = [context]
|
|
199
199
|
.concat(incomingParams.as.functionArguments)
|
|
200
|
-
.concat([${Object.keys(
|
|
200
|
+
.concat([${Object.keys(i).join(",")}])
|
|
201
201
|
.concat([exportedData, exportedTestData, exportedGlobalData]);
|
|
202
202
|
|
|
203
203
|
if(fileBuffer) {
|
|
@@ -210,73 +210,73 @@ Testim had missing write access to ${s||e}
|
|
|
210
210
|
injectCode(params, args, incomingParams, context, code);
|
|
211
211
|
});
|
|
212
212
|
})();
|
|
213
|
-
`,p=[],f=new
|
|
214
|
-
Action required: Please allow opening a websockets connection to ${be()} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Zo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let s={query:{projectId:e},requestTimeout:uy,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${be()}/${t}`,this._socket=Xu.connect(this.url,s),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let s={query:{projectId:e},requestTimeout:uy,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${be()}/${t}`,this._socket=Xu.connect(this.url,s),this.addSocketHandlers()}emitPromise(e,t){let s={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(s[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,py.default)(()=>ce(n(),sI),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(s).length>0&&Zo.error("Bad acknowledge from socket emit",{errorneousEvents:s})}),this.emitPromiseQueue}}});var dy={};q(dy,{remoteStepServiceSocketIO:()=>nI});var Qu,nI,my=I(()=>{"use strict";Yu();Qu=class extends Os{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,s){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&s(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},nI=new Qu});var fy={};q(fy,{remoteStepService:()=>_s});var Zu,ti,ep,_s,ea=I(()=>{"use strict";Qo();ae();ue();({REMOTE_STEP_SAVED:Zu}=Dt),ep=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(ti=(await Promise.resolve().then(()=>(my(),dy))).remoteStepServiceSocketIO,ti.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?Rt.addFilter(`${e}:remoteStep`,{resultId:e},[Zu]):ti.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){Rt.listenTo(`${e}:remoteStep`,[Zu],s=>s.resultId===e&&s.remoteStep&&s.remoteStep.status==="pending",s=>t(s.remoteStep));return}ti.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(Rt.removeFilter(`${e}:remoteStep`,[Zu]),Promise.resolve()):ti.unlistenToRemoteStep(e)}},_s=new ep});var tp,Fr,gy=I(()=>{"use strict";Yu();tp=class extends Os{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,s,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===s&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,s){return this.emitPromise("testResult:join",{resultId:t,testId:s})}async joinToTestResult(t,s){this.rooms[t]||this.joinRoom(t,s),await this.emitJoinRoom(t,s)}emitLeaveRoom(t,s){return this.emitPromise("testResult:leave",{resultId:t,testId:s})}leaveTestResult(t,s){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,s)):Promise.resolve()}getSocket(){return this._socket}},Fr=new tp});var yy={};q(yy,{testResultService:()=>jt});var hy,rp,jt,ta=I(()=>{"use strict";hy=require("events");Qo();ae();ue();gy();rp=class extends hy.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){Rt.onConnect=()=>this.emit("socket-connected");return}Fr.init(e),Fr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?Rt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Dt.TEST_RESULT_UPDATED,Dt.TEST_RESULT_CREATED]):Fr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){Rt.removeFilter(`${e}:testResult`,[Dt.TEST_RESULT_UPDATED,Dt.TEST_RESULT_CREATED]);return}await Fr.leaveTestResult(e,t)}listenToTestResult(e,t,s){if(O.flags.useNewWSCLI.isEnabled()){Rt.listenTo(`${e}:testResult`,[Dt.TEST_RESULT_UPDATED,Dt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>s(n));return}Fr.listenToTestResult(e,t,s)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Fr.getSocket()}},jt=new rp});var Ty,wy,vy,Re,iI,Sy,by,oI,ra,Ey=I(()=>{"use strict";Ty=R(require("lodash"));U();le();$e();Pr();pt();ye();oy();wy=R(require("p-retry")),vy=require("node:url");W();Yo();vs();ae();ea();ta();ye();Re=A("test-run-handler"),iI=3,Sy=20*1e3,by=r=>JSON.stringify(r).length<Sy,oI="Test couldn't be started",ra=class{constructor(e,t,s,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Or;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l,d;this._testStatus=s.testStatus,this._testId=s.testId,this._testOptimization=s.testOptimization,this._testName=s.name,this._testResultId=s.resultId,this._baseUrl=n.baseUrl||s.baseUrl||s.testConfig.baseUrl,this._nativeApp=s.nativeApp,this._overrideTestConfig=s.overrideTestConfig||s.testConfig,this._overrideTestConfigId=(c=s.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId,this._customCapabilities=n.customCapabilities||((l=s.customCapabilities)==null?void 0:l.capabilities);let a=!((d=s.runConfig)!=null&&d.isMobileWeb)&&n.browser;this._runConfig=a?pn(n.browser,n.saucelabs,n.browserstack):s.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get nativeApp(){return this._nativeApp}get executionName(){return this._executionName}get customCapabilities(){return this._customCapabilities}getSauceLabsAppPath(e,t){var s,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(s=this._nativeApp)==null?void 0:s.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var s;return this.isAppFromDevice?null:t?t[e]:(s=this._nativeApp)==null?void 0:s[e]}getAppPathByGridType(e,t,s){var n,i,o,a;return this.isAppFromDevice?null:s?(i=(n=s.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var s;let e=(s=this.nativeAppMetadata)==null?void 0:s.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return un(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return es(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?qi.FROM_DEVICE:qi.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${be()}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async isTestRecordedWithEnhancedMode(){return(await ei({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var s,n;let t={tokenV3:await Nt(),refreshToken:mo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:mm(),remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},...Vc()&&{betterstack:Vc()},userAccessKey:await fo()};if(this._options.disableMockNetwork&&mt("user-disable-mock"),t.lightweightMode&&((s=this._options.lightweightMode)!=null&&s.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=by(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,c=this.testId;o?(Object.assign(t,{runData:i}),Re.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Re.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Sy} characters)`),Object.assign(t,{isLocalRun:!!(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let i=await Zn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Re.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testOptimization(){return this._testOptimization}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&by(e))return;let s=async()=>{try{return await ip(this._options.project,this._testId,this._testResultId,e)}catch(o){return Re.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await s();return await this._testRunStatus.waitForExecutionStartedFinished(),np(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===oI||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return!!this.testInfraIssueRetryCount}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){M("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},s=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&s.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=o||{};M("before Runtime.evaluate"),await(0,wy.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return M("after Runtime.evaluate"),l.value}catch(o){throw Re.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let s;try{s=new vy.URL(e)}catch{return}let{username:n,password:i}=s;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let s=!1,n=i=>{if(!s){if(this.isRetryKeyMismatch(i)){Re.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(Re.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),s=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:c,branch:l,_options:{project:d}}=this;try{let m=await Ur(a,c,d,l);n(m),s||setTimeout(o,3e3)}catch(m){Re.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else jt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:s},branch:n}=this;try{let i=await Ur(e,t,s,n),o=["running","completed"];if(o.includes(i.status))return Re.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Re.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ae.TEST_START_TIMEOUT_MSG)}catch(i){throw Re.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Ae.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await jt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(s=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Re.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),s(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||jt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Re.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,s(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Ty.debounce(async()=>{try{await jt.joinToTestResult(this._testResultId,this.testId)}catch(o){Re.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Ur(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Re.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(Re.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,s(o),!0):!1}catch(o){return Re.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)jt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await sp(this._testResultId,this._options.project,this.retryKey);a?await e()||(Re.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Re.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&jt.off("socket-connected",e)}}listenToRemoteStep(e){_s.listenToRemoteStep(this.testResultId,t=>{iy(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:iI;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,s;return!!((s=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)!=null&&s.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=ne(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var sa,Iy=I(()=>{"use strict";Ey();sa=class{constructor(e,t,s,n,i,o){this.pendingAppUploads=new Map;let a=new Set(s.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=s.map(c=>new ra(e,t,c,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return!!this._waitingTests.length}}});async function xy(r,e){var t;return(t=r.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&r.testId?{tests:[r.testId.map(n=>({testId:n,testConfig:{},resultId:ne()}))]}:await cp({projectId:r.project,labels:r.label,testIds:r.testId,testNames:r.name,testConfigNames:r.testConfigNames,suiteNames:r.suites,suiteIds:r.suiteIds,branch:e,rerunFailedByRunId:r.rerunFailedByRunId,testConfigIds:r.testConfigIds,intersections:r.intersections})}function op(r){let e=Object.keys(r).length,t=Object.keys(r).reduce((s,n)=>s+(r[n].success===!0?1:0),0);return e===t}async function ap(r,e){let t=r.mode===J.EXTENSION?Br:ri,s=Ry.difference(cn(r,e),t);if(s.length>0)throw mt("invalid-config-run",{browser:s.join(", "),mode:"runner"}),new C(`browser type <${s}> is not supported in ${r.mode} mode.`);return e}var Ry,Br,ri,na=I(()=>{"use strict";Ry=R(require("lodash"));U();Pr();ye();Q();ae();Br=["edge-chromium","chrome"],ri=[...Br,"firefox","safari","safari technology preview"]});var aI,cI,lI,si,lp=I(()=>{"use strict";ds();ys();W();aI=A("worker-utils"),cI=async(r,e,t)=>{e&&await Hl(r,t)},lI=async(r,e,t)=>{await hu(r,e,t)},si=async(r,e,t,s,n,i)=>{aI.info("releasing player",{hasPlayer:!!i});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await cI(r,e,t),n==="redis"&&await lI(r,s,t)}}});function mI(r,e,t,s){return{testId:r,reason:s,name:e,resultId:t,success:!1}}var aa,Py,ca,la,ky,gt,Cy,Ay,ia,up,jr,uI,pp,pI,Yt,dI,oa,fI,$t,ni=I(()=>{"use strict";aa=R(require("ms")),Py=R(require("lodash")),ca=R(require("p-retry")),la=R(require("dayjs")),ky=R(require("dayjs/plugin/duration"));U();$e();ds();ys();ye();W();lp();Ft();Vo();ue();ea();ta();pt();Ve();ae();Q();la.default.extend(ky.default);gt=A("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Cy,TEST_START_TIMEOUT_MSG:Ay,TEST_COMPLETE_TIMEOUT_MSG:ia,TEST_REACHED_CUSTOM_TIMEOUT_MSG:up}=Ae,{SETUP_TIMEOUT:jr,NETWORK_ERROR:uI,GRID_ERROR:pp,BROWSER_CLOSED:pI,SELENIUM_ERROR:Yt,UNKNOWN_ERROR:dI,MOBILE_SESSION_ERROR:oa}=Yr;fI=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],$t=class{constructor(e,t,s,n,i,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=s;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new Xt;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let s=await mg(e,t.executionId,this.options,this.id,t.testResultId);return this.onGridSlot(t.testResultId,s),s}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Z.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new en(!0)}async getBrowserOnce(e,t,s,n){throw new en(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),gt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!et({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:he.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=ts(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,s=e.isAppForIosVirtualDevice;if(t||s){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:he.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:s}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=O.flags.increaseTDCRequestTimeout.isEnabled(),s=Er(O.flags.appiumConnectionRequestTimeout.getValue(),(0,aa.default)("2m")),n=Er(O.flags.appiumConnectionRetryCount.getValue(),1),i=s*n;return e===N.BROWSERSTACK||t&&e===N.TESTIM_TDC?i+(0,aa.default)("10m"):i+(0,aa.default)("1m")}getSessionTimeout(){if(ir(this.options)){let t=this.options.gridData.type,s=this.calculateMobileTestTimeout(t);return Math.max(s,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,ca.default)(async()=>{let n=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ae.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,ca.default)(async()=>{var n,i;let s=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await ce(Bg(o,a,this.id),this.options.getBrowserTimeout,Ae.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,s)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let s={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof sr?gt.info("could not get grid slot due to concurrency issue",s):gt.error("error getting grid slot",{error:e,...s}),await ie(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let s=(i=this.userData)==null?void 0:i.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let c=this.options.getBrowserRetries-o;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,ca.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let p=await fg(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1});this.options.gridData.provider=p.provider,this.options.gridData.host=p.host,this.options.gridData.failedGetBrowserAttempts=l,M("before getBrowserOnce");let f=await ce(this.getBrowserOnce(e,t,m,p),this.getSessionTimeout(),Ae.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Z.onGetBrowserSuccess(this.id,s),m||f}catch(p){let f={...a,failedGetBrowserAttempts:l,id:this.options.gridData.gridId},h=this.options.mode===J.APPIUM?"device":"browser";throw gt.error(`error getting ${h} from grid`,{error:p,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,s,++l),m.onDone(),!(p instanceof _t)&&this.options.mode!==J.APPIUM&&await ie(this.options.getBrowserTimeout-(Date.now()-d)),p}},{retries:c-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(o){throw await si(this.id,this.releaseSlotOnTestFinished,s,this.options.company.companyId,this.options.slotService,n),[_t,Kr].some(a=>o instanceof a)?o:o instanceof ot?new vr(o,pp):new vr(o,Yt)}return n}async runTest(e,t,s){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=ir(this.options)&&this.handleMobileTest(e);if(o)return o;M("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,s,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await Nt(),await this.runTestOnce(e,l)}finally{await si(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...s){var f,h;let n=async(g,b)=>{var L,j;if(et(g,this.options)||ts(O,(L=this.options.gridData)==null?void 0:L.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...s);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let v=V=>b==null?void 0:b.message.includes(V),y=b&&b instanceof vr,w=v(Ay),S=b&&(v(ia)||v(up)||w&&!e.retryOnInfraErrors),x=!!v(up)&&!!this.testRunTimeout,B=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||w)&&e.retryOnInfraErrors,G=S&&e.hasMoreTimeoutRetries()&&!x,E=e.hasMoreRetries()&&!y&&!S,k=!g.success&&(E||G||B);try{let V=e.retryKey;g.testRetryKey=V;let K=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,k,K),await this.runTestCleanup(),k){if(G&&await e.startNewTimeoutRetry(),B){gt.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:b});let z=(j=this.options.projectData)==null?void 0:j.projectId,re=e.testResultId,ge=e.testId;await ua(z,re,ge,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return E&&!B&&!G&&await e.startNewRetry(),gt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:S,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await p(k)}t(this.id,...s);return}catch(V){if(V instanceof rr)return;gt.error("failed to process test result",{error:V}),t(this.id,...s);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
215
|
-
Please make sure the CLI has stable access to the internet. ${
|
|
216
|
-
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:"type"in g&&g.type==="KEEP_ALIVE_FAILED"?{errorType:Yt,reason:"Test terminated due to repeated keep alive failures. The browser may have become unresponsive or the test environment may be unstable."}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:Yt,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:Yt,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:Yt,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:Yt,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:dI,reason:y}},c=async g=>{var w;let b=await el();!b&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),gt.warn("error on run",{err:g});let T=(w=this.userData)==null?void 0:w.projectId,{errorType:v,reason:y}=this.options.mode===J.APPIUM?o(g):a(g,b);ua(T,this.testResultId,this.testId,{status:on.COMPLETED,success:!1,reason:y,errorType:v,testRetryKey:e.retryKey,setupStepResult:{status:on.COMPLETED,success:!1,reason:y,errorType:v}},e.remoteRunId).catch(S=>gt.error("Failed to update test result after test failed",{error:S})),await n(mI(this.testId,this.testName,this.testResultId,y),g)},l=async g=>{var w;let b=this.testId,T=this.testResultId,v=(w=this.userData)==null?void 0:w.projectId,y=this.branch;if(!b||!T||!v||!y)return gt.warn("Test failed. Not enough data to recover results via API",{err:g}),c(g);try{let S=await Ur(b,T,v,y);if(gt.warn("Test failed. Got results via API",{err:g,testResult:Py.default.omit(S,fI),resultId:T}),S&&S.status===on.COMPLETED&&!g.message.includes(ia))return await n(S);throw g}catch(S){return S!==g&>.error("Failed to fetch test results from server",{testId:b,resultId:T,projectId:v,branch:y,err:S}),c(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===J.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),p=async g=>{try{await Promise.all([!m&&_s.joinToRemoteStep(this.testResultId),!d&&jt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==J.APPIUM&&e.validateRunConfig();let b=await this.runTest(e,this.customExtensionLocalLocation,g);await n(b),M("After onRunComplete"),t(this.id,...s)}catch(b){await l(b),t(this.id,...s)}finally{m||_s.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,p()}}});var _y,Oy,Ls,dp=I(()=>{"use strict";U();_y=R(require("p-retry"));U();W();Q();Oy=A("window-utils"),Ls=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function s(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(s,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(s){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:s.x,top:s.y,behavior:"instant"}):window.scrollTo(s.x,s.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let s=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return Oy.warn("selenium navigation failed. retrying to navigate",{err:i}),await ie(1500),s(n-1);throw!i.seleniumStack&&o&&Oy.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([s(),ie(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ie(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let s=document.body,n=document.documentElement,i=Math.max(s.scrollHeight,s.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(s.scrollWidth,s.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ie(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let s;if(typeof window<"u"&&window.location!==void 0)s=window.location;else return!1;return s.href!=="chrome-error://chromewebdata/"&&s.href!=="safari-resource:/ErrorPage.html"&&!s.href.startsWith("res://ieframe.dll/http_404.htm")&&!s.href.startsWith("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")}if(!(await this.driver.executeJS(e)).value)throw new _t("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,_y.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var mp,Ds,fp=I(()=>{"use strict";W();mp=A("cookies-utils"),Ds=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(s){throw mp.error("failed to set cookie",{err:s}),s}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw mp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw mp.error("failed to remove cookie",{err:t}),t}}}});var gp,pa,Ly=I(()=>{"use strict";gp=R(require("p-retry")),pa=class{constructor(e,t,s={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=s;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,s=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([s,this.driver.takeScreenshot()]),[i,o]=await(0,gp.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,s=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,gp.default)(i,{retries:t,minTimeout:s,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function gI(r){let{loadImage:e}=await Ne("canvas"),t=Buffer.from(r,"base64");return await e(t)}async function da(r){let e=await gI(r);return{width:e.width,height:e.height}}async function Dy(r,e){let{createCanvas:t,Image:s}=await Ne("canvas"),n=t(e.width,e.height),i=n.getContext("2d"),o=new s;return o.src=`data:image/png;base64,${r}`,await new Promise((a,c)=>{o.onload=()=>a(),o.onerror=c}),i.drawImage(o,e.left,e.top,e.width,e.height,0,0,e.width,e.height),n.toDataURL("image/png")}async function Ny(r,e){let t="image/png",{createCanvas:s,Image:n}=await Ne("canvas"),i=s(r.width,r.height),o=i.getContext("2d");for(let c of e){let l=c.image.match(/^data:([^;]*);base64,(.*)$/),d=l[1],m=l[2],p=new n;p.src=`data:${d};base64,${m}`,await new Promise((f,h)=>{p.onload=()=>f(),p.onerror=h}),o.drawImage(p,c.position.left,c.position.top,c.size.width,c.size.height)}return i.toDataURL(t)}var hp=I(()=>{"use strict";ws()});async function My(r,e){let t=e.image||e,s=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let i=r.offset||{top:0,left:0};if(i.top*=s,i.left*=s,!r.elementRect)return hI.warn("missing elementRect",Uy.omit(r,"image")),{};let{elementRect:o}=r,a=o.left*s+i.left*s,c=o.top*s+i.top*s,l=o.width*s,d=o.height*s;a<0&&(l+=a,l=Math.max(l,0),a=0),c<0&&(d+=c,d=Math.max(d,0),c=0);let{width:m,height:p}=await da(n[1]);if(a+l>m&&(l=m-a),c+d>p&&(d=p-c),d<=0||l<=0)throw new yp("height or width is equal or lower than zero");return{elementImage:await Dy(n[1],{left:a,top:c,width:l,height:d})}}function yI(r,e){return Ny(r,e)}async function bI(){}async function TI(r){function e(i){let o=r[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await bI(r[i]);return{key:i,url:o}}let s=await oe(Object.keys(r).filter(e),t),n=Object.fromEntries(s.map(i=>[i.key,i.url]));return Object.assign(r,n)}function Fy(r,e){return e||=1,r||={left:0,top:0,width:0,height:0},{left:e*Math.round(r.left),top:e*Math.round(r.top),width:e*Math.round(r.width),height:e*Math.round(r.height),pixelRatio:e}}var Uy,hI,yp,ma,By=I(()=>{"use strict";Uy=R(require("lodash"));U();hp();W();hI=A("image-capture-utils"),yp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};ma=class{constructor(e,t,s){this.windowUtils=t;this.screenshotUtils=s}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),s=await My(e,t);return Object.assign(s,{screenImage:t.image,absoluteScreenHighlight:Fy(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return TI({screenImage:t.image,absoluteScreenHighlight:Fy(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:s}=this,n=()=>ie(250),i=!!e;async function o(p,f){i?await t.scrollToPositionWithoutAnimation(p):await t.scrollToPosition(p),await n();let h=await s.takeScreenshot(),g=await My({elementRect:f},h);return{position:{left:p.x+f.left,top:p.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(p){let f=[];for(let h of p){let g=await o(h.scrollPos,h.cropData);f.push(g)}return f}function c(p,f){let h=Math.max(p.width,f.width),g=f.width,b=Math.max(p.height,f.height),T=f.height,v=Array.from({length:Math.ceil(h/g)},(w,S)=>({scrollX:Math.min(S*g,h-g),cropX:S*g-Math.min(S*g,h-g),cropW:g-(S*g-Math.min(S*g,h-g))})),y=Array.from({length:Math.ceil(b/T)},(w,S)=>({scrollY:Math.min(S*T,b-T),cropY:S*T-Math.min(S*T,b-T),cropH:T-(S*T-Math.min(S*T,b-T))}));return v.flatMap(w=>y.map(S=>({scrollPos:{x:w.scrollX,y:S.scrollY},cropData:{top:S.cropY,left:w.cropX,width:w.cropW,height:S.cropH}})))}async function l(p,f){let h=await t.getCurrentScrollPosition(),g=c(p,f),b=await a(g);return await t.scrollToPosition(h),yI(p,b)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(d,m)}}});var jy,$y,fa,ga,Wy=I(()=>{"use strict";jy=R(require("p-retry")),$y=R(require("semver"));U();W();dp();Ly();By();Se();fa=A("tab-service"),ga=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(s=>!t[s].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(s=>{let n=this.getTabInfo(e,s);return`tabId=${s}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,s,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),fa.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${s}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,s,n)}addOpenerStepId(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s}addOpenerStep(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=s.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let s=this.getAllTabInfos(e);Object.keys(s).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,s,n,i={}){let o=await this.getTabDetails(t,e,i),a=ne();function c(l){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!l.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:s,from:this.getTabInfo(e,o.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,s,n,i={}){let o=await this.buildTabInfo(e,t,s,n,i),a=new Ls(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new ma(t,a,new pa(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let s=this.sessionTabs[e].tabInfos[t];return this._utils[s.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(s=>this._utils[s].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let s=this.getAllTabInfos(e),n=Object.keys(s).map(o=>s[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,s){let n=s.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,s,n){let{urlUtils:i}=ee(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),c=n(o),l=n(a),d=s.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===c);return c===l&&d.length===1}isSameTab(e,t,s){let{tabMatcher:n}=ee();if(n){let l=this.getAllTabInfos(e),d=Object.keys(l).map(m=>l[m]);return n.isSameTab(d,t,s)}if(t.isMain&&s.isMain||t.openerStepId&&s.openerStepId&&t.openerStepId===s.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(l=>i[l].url);if(this.exactUrlMatch(t,s,o))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,s,o,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,s,o,c)||t.order===s.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(s=>t[s]).find(s=>s.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(s=>t[s].isMain)}async isMainTabExists(e){return!!this.getMainTabId(e)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(s=>this.removeTabInfo(e,s))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(s=>!t[s].isMain).forEach(s=>this.removeTabInfo(e,s)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:s=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||s)return this.driver.switchTab(e)}async getTabDetails(e,t,s={}){try{if(await this.switchTab(e,t,s),s.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");s.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){fa.error("failed to get url or title",{err:i})}}catch(n){fa.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(s=>!this.getAllTabIds(e).includes(s))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ie(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let s=this.getAllTabInfos(e);if(Object.keys(s).find(o=>s[o].openerStepId===t))return;if(this.pendingTabs[e]){fa.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let i=await this.waitForTabToOpen(e);await this.addNewTab(e,i,this.pendingTabs[e]),this.addFrameHandler(i),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,jy.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=$y.lt(e._version||e.version,"1.2.0"),s=!!e.parameterValues,n=s&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!s||n)}async getTabIdByTabInfo(e,t){var c,l;let{tabMatcher:s,commonConstants:n}=ee();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((c=t.useCurrentTab)!=null&&c.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(l=t.tabInfo)==null?void 0:l.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=s.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(p=>d.message.toLowerCase().includes(p)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var bp,ha,Tp=I(()=>{"use strict";bp=class{select(){return console.log(`
|
|
213
|
+
`,p=[],f=new qh.Worker(m,{eval:!0});try{return await ae(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:b}=g,T={...b,tstConsoleLogs:p};mt.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&p.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?mt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):mt.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:p,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{mt.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),n)}catch(h){if(!(h instanceof ue))throw h;return mt.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:p,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function DE(s){try{await Vh.promises.rm(s,{recursive:!0,force:!0})}catch(e){mt.warn("failed to remove install npm packages folder",{err:e})}}function zh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function xs(s,e,t,r,i,n){let o=zh(i,e,s,t),{data:a}=await NE(o,r,n);return a}async function Cs(s,e,t,r,i,n,o,a,c,l){var g;let d=r.computePackagePathFromPackageJsonExports||O.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(b=>{if(d){let T=Mf(b.testimPackageLocalLocation);return[b.paramName,Rs.join(b.testimPackageLocalLocation,T)]}return[b.paramName,b.testimPackageLocalLocation]}))||[]),p=zh(o,i,e,n);if(l){let b=await Ui(l);b&&(c=b)}return Buffer.isBuffer(c)&&(mt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString()),c==="data:"&&(mt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c="data:,"),{...await LE(p,t,r,s,m,a,c),nodeVersion:process.version}}async function NE(s,e,t){let r=e.map(l=>`${l.packageName}@${l.packageVersion}`),i=Kh(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?i:Rs.join(i,`/${s}`),a=global.proxyUri;async function c(){let l="";try{if(l=await Cl(o,r,a,t),mt.info("npm package install finished",{transactionId:s,output:l,timeout:t}),Number(l.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let p=Df(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${p}`,packageLocalLocation:Rs.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw mt.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await ae(c(),t)}catch(l){throw l instanceof ue&&mt.warn("timeout to install package",{packages:r,transactionId:s,err:l,timeout:t}),l}}function Kh(){return Rs.join(Gh.tmpdir(),"/testim_local_packages")}function ME(){let s=Kh();return DE(s)}var Vh,Gh,Rs,Hh,qh,mt,As=I(()=>{"use strict";Vh=R(require("fs")),Gh=R(require("os")),Rs=R(require("path"));U();ls();Hh=R(require("data-uri-to-buffer")),qh=require("worker_threads");Q();W();ye();ls();pe();mt=A("cli-service");ME().catch(s=>mt.warn("failed to clean local package folder",{err:s}))});var pr={};q(pr,{run:()=>UE});function FE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),i=JSON.stringify(s).length>r;return t?i:!1}catch{return!1}}var UE,Jh=I(()=>{"use strict";As();Q();pe();UE=async(s,e,t)=>{let{code:r,stepId:i,incomingParams:n,context:o,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:d,fileDataUrl:m,s3filepath:p}=e.data;try{let f=await Cs(r,i,n,o,a,c,l,d,m,p);return f&&FE({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ue?new Error("Timeout while running action"):f}}});var Vu={};q(Vu,{run:()=>BE});var BE,Xh=I(()=>{"use strict";As();Q();BE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:i,stepResultId:n,packageData:o,timeout:a}=e.data;try{return{data:await xs(t,r,i,o,n,a),success:!0}}catch(c){if(c instanceof _t)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof ue)return{success:!1,code:"timeout"};throw c}}});async function Qh(s,e,t,r){try{return await Gu(s,e,t,r)}catch{Jo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function $E(s,e,t,r,i){return Jo.info("finished to run remote step",{stepId:t,sessionId:i}),await Qh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Yh(s,e,t,r,i){return Jo.info("failed to run remote step",{stepId:t,sessionId:i,failureReason:r}),await Qh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Zh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:i,projectData:n}=s,o=t.type,a=e.getSessionId(),c=t.id;Jo.info("start play remote step",{stepType:o,stepId:c,sessionId:a});let l=jE[o];if(!l)return await Yh(i,r,c,`Failed to find step type ${o}`,a);try{let d=await l.run(e,t,n);return await $E(i,r,c,d,a)}catch(d){return await Yh(i,r,c,d.message,a)}}var Jo,jE,ey=I(()=>{"use strict";Jh();ye();Xh();W();Jo=A("step-playback"),jE={"cli-validation-code-step":pr,"cli-wait-for-code-step":pr,"cli-action-code-step":pr,"cli-api-code-step":pr,"cli-condition-step":pr,"cli-download-code-step":pr,"node-package":Vu}});var ry={};q(ry,{preloadTests:()=>Yi});async function Yi(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ct(async()=>{let t=await ne(s.testId,r=>Qi({...e,testId:r}),{concurrency:2});return ty.keyBy(t,"testData.id")},"loadTests",VE,[e,s.testId])()}var ty,VE,Xo=I(()=>{"use strict";ty=R(require("lodash"));zt();ye();U();VE=1e3*60*60*10});var Hu,sy,Nr,GE,qu,It,Yo=I(()=>{"use strict";U();wt();Hu=R(require("ws")),sy=require("events");W();le();Nr=A("socket-service"),GE=5e3,qu=class extends sy.EventEmitter{constructor(){super(...arguments);this.clientId=ce();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Nr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),GE)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Nr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(Zd);return Dt().then(i=>new Promise(n=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Hu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${i}`,o),this.ws.on("open",()=>{var a;return Nr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),n()}),this.ws.on("close",a=>{Nr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Hu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Nr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){Nr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Nr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,i){let n=o=>{r(o)&&(i(o),this.removeListener(t,n))};this.on(t,n)}listenTo(t,r,i,n){function o(c){i(c)&&n(c)}(Array.isArray(r)?r:[r]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=o.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,i,n=!1){return new Promise(o=>{let a=ce(),c={query:r,id:a,type:i,fullDocument:n};this.listenOnce("add-filter:done",l=>l.id===a,o),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(i=>{let n=this.listeners[`${t}:${i}`];n&&(delete this.listeners[`${t}:${i}`],n.forEach(o=>this.removeListener(i,o)))})}removeFilter(t,r){let i=this.filterMap[t];if(!i)return;let n=Array.isArray(r)?r:[r];this.removeListeners(t,n),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:i})}},It=new qu});var ny,zu,HE,qE,zE,iy,Qo,Ps,Ku=I(()=>{"use strict";ny=R(require("p-retry")),zu=R(require("socket.io-client"));le();U();W();HE=50,qE=10,zE=5e3,iy=10*1e3,Qo=A("base socket service"),Ps=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Qo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var i;let r=this.rooms[t];(i=this.emitJoinRoom)==null||i.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let i="websocket";try{i=this._socket.io.engine.transport.name}catch{}Qo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${i}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===qE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=HE)throw new Error(`Can't connect to Testim Servers.
|
|
214
|
+
Action required: Please allow opening a websockets connection to ${be()} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Qo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:iy,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(i=>{this.url=`${be()}/${t}`,this._socket=zu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",i),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:iy,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${be()}/${t}`,this._socket=zu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},i=()=>new Promise((n,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?n():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,ny.default)(()=>ae(i(),zE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Qo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var oy={};q(oy,{remoteStepServiceSocketIO:()=>KE});var Ju,KE,ay=I(()=>{"use strict";Ku();Ju=class extends Ps{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.remoteStep&&i.remoteStep.status==="pending"&&r(i.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},KE=new Ju});var cy={};q(cy,{remoteStepService:()=>ks});var Xu,Zi,Yu,ks,Zo=I(()=>{"use strict";Yo();oe();pe();({REMOTE_STEP_SAVED:Xu}=Lt),Yu=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Zi=(await Promise.resolve().then(()=>(ay(),oy))).remoteStepServiceSocketIO,Zi.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?It.addFilter(`${e}:remoteStep`,{resultId:e},[Xu]):Zi.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){It.listenTo(`${e}:remoteStep`,[Xu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Zi.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(It.removeFilter(`${e}:remoteStep`,[Xu]),Promise.resolve()):Zi.unlistenToRemoteStep(e)}},ks=new Yu});var Qu,Mr,ly=I(()=>{"use strict";Ku();Qu=class extends Ps{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,i){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.testId===r&&i(n.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Mr=new Qu});var py={};q(py,{testResultService:()=>Bt});var uy,Zu,Bt,ea=I(()=>{"use strict";uy=require("events");Yo();oe();pe();ly();Zu=class extends uy.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){It.onConnect=()=>this.emit("socket-connected");return}Mr.init(e),Mr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?It.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Lt.TEST_RESULT_UPDATED,Lt.TEST_RESULT_CREATED]):Mr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){It.removeFilter(`${e}:testResult`,[Lt.TEST_RESULT_UPDATED,Lt.TEST_RESULT_CREATED]);return}await Mr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){It.listenTo(`${e}:testResult`,[Lt.TEST_RESULT_UPDATED,Lt.TEST_RESULT_CREATED],i=>i.resultId===e&&i.testId===t,i=>r(i));return}Mr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Mr.getSocket()}},Bt=new Zu});var my,fy,gy,Re,JE,hy,dy,XE,ta,yy=I(()=>{"use strict";my=R(require("lodash"));U();le();je();Ar();wt();ye();ey();fy=R(require("p-retry")),gy=require("node:url");W();Xo();Ts();oe();Zo();ea();ye();Re=A("test-run-handler"),JE=3,hy=20*1e3,dy=s=>JSON.stringify(s).length<hy,XE="Test couldn't be started",ta=class{constructor(e,t,r,i,n,o){this._executionId=e;this._executionName=t;this._options=i;this._branch=n;this._testRunStatus=o;this.seleniumPerfStats=new kr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l,d;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=i.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=i.retries,this._remoteRunId=i.remoteRunId,this._customCapabilities=i.customCapabilities||((l=r.customCapabilities)==null?void 0:l.capabilities);let a=!((d=r.runConfig)!=null&&d.isMobileWeb)&&i.browser;this._runConfig=a?ai(i.browser,i.saucelabs,i.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get nativeApp(){return this._nativeApp}get executionName(){return this._executionName}get customCapabilities(){return this._customCapabilities}getSauceLabsAppPath(e,t){var r,i;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(i=this._nativeApp)==null?void 0:i.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var i,n,o,a;return this.isAppFromDevice?null:r?(n=(i=r.gridData)==null?void 0:i[e])==null?void 0:n[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return oi(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Zr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Hn.FROM_DEVICE:Hn.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${be()}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async isTestRecordedWithEnhancedMode(){return(await Qi({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,i;let t={tokenV3:await Dt(),refreshToken:po(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:am(),remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},...Wc()&&{betterstack:Wc()},userAccessKey:await mo()};if(this._options.disableMockNetwork&&pt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let n=this.runData,o=dy(n);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(n).length,c=this.testId;o?(Object.assign(t,{runData:n}),Re.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Re.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${hy} characters)`),Object.assign(t,{isLocalRun:!!(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((i=this._options.lightweightMode)!=null&&i.preloadTests&&this._options.useChromeLauncher){let n=await Yi(this._options);Object.assign(t,{preloadedTest:n[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Re.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testOptimization(){return this._testOptimization}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var n;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((n=this._options.lightweightMode)!=null&&n.disableResults&&!t&&dy(e))return;let r=async()=>{try{return await rp(this._options.project,this._testId,this._testResultId,e)}catch(o){return Re.error("failed to upload run data artifact (runner)",{err:o}),""}},i=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),tp(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=i(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===XE||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return!!this.testInfraIssueRetryCount}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){M("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:i}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:n}=t.find(o=>o.type==="page")||{};if(!i)throw new Error("Tricentis Testim extension not found");if(!n)throw new Error("AUT target not found");try{M("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:i,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=o||{};M("before Runtime.evaluate"),await(0,fy.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return M("after Runtime.evaluate"),l.value}catch(o){throw Re.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new gy.URL(e)}catch{return}let{username:i,password:n}=r;if(i||n)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,i=n=>{if(!r){if(this.isRetryKeyMismatch(n)){Re.warn(`ignoring result update for on started due to retry key mismatch, got ${n.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(n.status)&&(n.resultId=this.testResultId,n.status==="completed"&&!this.isRerunOnInfraError(n.reason)&&(Re.info("setting _wasCompletedOnStartedCheck to true",{testResult:n,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=n),r=!0,t(n))}};if(this._options.disableSockets){let n=Date.now()+e,o=async()=>{if(Date.now()>n)return;let{testId:a,testResultId:c,branch:l,_options:{project:d}}=this;try{let m=await Fr(a,c,d,l);i(m),r||setTimeout(o,3e3)}catch(m){Re.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else Bt.listenToTestResult(this._testResultId,this._testId,i)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:i}=this;try{let n=await Fr(e,t,r,i),o=["running","completed"];if(o.includes(n.status))return Re.info(`get status: ${n.status} after not get test started status`,{testId:e,testResultId:t,branch:i}),n;throw Re.error(`test not start test status: ${n.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:i}),new Error(Ae.TEST_START_TIMEOUT_MSG)}catch(n){throw Re.error("failed to get test result after test start timeout",{err:n,testId:e,testResultId:t,branch:i}),new Error(Ae.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Bt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Re.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Bt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Re.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let i=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),n=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=my.debounce(async()=>{try{await Bt.joinToTestResult(this._testResultId,this.testId)}catch(o){Re.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Fr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Re.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(Re.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return Re.warn("Error while trying to check status on socket connect",o),!1}},i,{maxWait:n}),!this._options.disableSockets)Bt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await ep(this._testResultId,this._options.project,this.retryKey);a?await e()||(Re.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Re.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Bt.off("socket-connected",e)}}listenToRemoteStep(e){ks.listenToRemoteStep(this.testResultId,t=>{Zh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:JE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return!!((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)!=null&&r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=ce(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var ra,by=I(()=>{"use strict";yy();ra=class{constructor(e,t,r,i,n,o){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!i.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),i.appId&&this.pendingAppUploads.set(i.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new ta(e,t,c,i,n,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return!!this._waitingTests.length}}});async function wy(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(i=>({testId:i,testConfig:{},resultId:ce()}))]}:await np({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function sp(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,i)=>r+(s[i].success===!0?1:0),0);return e===t}async function ip(s,e){let t=s.mode===J.EXTENSION?Ur:en,r=Ty.difference(ii(s,e),t);if(r.length>0)throw pt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Ty,Ur,en,sa=I(()=>{"use strict";Ty=R(require("lodash"));U();Ar();ye();Q();oe();Ur=["edge-chromium","chrome"],en=[...Ur,"firefox","safari","safari technology preview"]});var YE,QE,ZE,tn,op=I(()=>{"use strict";ps();hs();W();YE=A("worker-utils"),QE=async(s,e,t)=>{e&&await Wl(s,t)},ZE=async(s,e,t)=>{await mu(s,e,t)},tn=async(s,e,t,r,i,n)=>{YE.info("releasing player",{hasPlayer:!!n});try{await(n==null?void 0:n.onDone())}finally{i==="mongo"&&await QE(s,e,t),i==="redis"&&await ZE(s,r,t)}}});function sI(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var oa,Ey,aa,ca,Iy,ft,vy,Sy,ia,ap,Br,eI,cp,tI,Xt,rI,na,iI,jt,rn=I(()=>{"use strict";oa=R(require("ms")),Ey=R(require("lodash")),aa=R(require("p-retry")),ca=R(require("dayjs")),Iy=R(require("dayjs/plugin/duration"));U();je();ps();hs();ye();W();op();Mt();Wo();pe();Zo();ea();wt();We();oe();Q();ca.default.extend(Iy.default);ft=A("base-worker"),{GET_BROWSER_TIMEOUT_MSG:vy,TEST_START_TIMEOUT_MSG:Sy,TEST_COMPLETE_TIMEOUT_MSG:ia,TEST_REACHED_CUSTOM_TIMEOUT_MSG:ap}=Ae,{SETUP_TIMEOUT:Br,NETWORK_ERROR:eI,GRID_ERROR:cp,BROWSER_CLOSED:tI,SELENIUM_ERROR:Xt,UNKNOWN_ERROR:rI,MOBILE_SESSION_ERROR:na}=Xr;iI=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],jt=class{constructor(e,t,r,i,n,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=i;this.onTestStarted=n;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new Jt;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await ag(e,t.executionId,this.options,this.id,t.testResultId);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Z.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Ys(!0)}async getBrowserOnce(e,t,r,i){throw new Ys(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),ft.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!Ze({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:he.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var i,n;if(((i=this.options.gridData)==null?void 0:i.mode)==="local")return;let t=es(O,(n=this.options.gridData)==null?void 0:n.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:he.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=O.flags.increaseTDCRequestTimeout.isEnabled(),r=Sr(O.flags.appiumConnectionRequestTimeout.getValue(),(0,oa.default)("2m")),i=Sr(O.flags.appiumConnectionRetryCount.getValue(),1),n=r*i;return e===N.BROWSERSTACK||t&&e===N.TESTIM_TDC?n+(0,oa.default)("10m"):n+(0,oa.default)("1m")}getSessionTimeout(){if(ir(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,aa.default)(async()=>{let i=Date.now();try{return await ae(this.getSlotOnce(e),this.options.getBrowserTimeout,Ae.GET_BROWSER_TIMEOUT_MSG)}catch(n){return t++,await this.handleGetSlotError(n,i)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,aa.default)(async()=>{var i,n;let r=Date.now();try{let o=(i=this.options.company)==null?void 0:i.companyId,a=(n=this.options.projectData)==null?void 0:n.projectId;return await ae(Lg(o,a,this.id),this.options.getBrowserTimeout,Ae.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof rr?ft.info("could not get grid slot due to concurrency issue",r):ft.error("error getting grid slot",{error:e,...r}),await ie(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var n;let r=(n=this.userData)==null?void 0:n.projectId,i;try{M("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let c=this.options.getBrowserRetries-o;if(!c)throw new Error("No free browser slots in desired grid");let l=0;i=await(0,aa.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let p=await cg(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1});this.options.gridData.provider=p.provider,this.options.gridData.host=p.host,this.options.gridData.failedGetBrowserAttempts=l,M("before getBrowserOnce");let f=await ae(this.getBrowserOnce(e,t,m,p),this.getSessionTimeout(),Ae.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Z.onGetBrowserSuccess(this.id,r),m||f}catch(p){let f={...a,failedGetBrowserAttempts:l,id:this.options.gridData.gridId},h=this.options.mode===J.APPIUM?"device":"browser";throw ft.error(`error getting ${h} from grid`,{error:p,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,r,++l),m.onDone(),!(p instanceof Ot)&&this.options.mode!==J.APPIUM&&await ie(this.options.getBrowserTimeout-(Date.now()-d)),p}},{retries:c-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(o){throw await tn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,i),[Ot,zr].some(a=>o instanceof a)?o:o instanceof nt?new wr(o,cp):new wr(o,Xt)}return i}async runTest(e,t,r){var d;M("inside runTest");let i=(d=this.userData)==null?void 0:d.projectId,n=this.handleQuarantine(e);if(n)return n;let o=ir(this.options)&&this.handleMobileTest(e);if(o)return o;M("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await Dt(),await this.runTestOnce(e,l)}finally{await tn(this.id,this.releaseSlotOnTestFinished,i,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let i=async(g,b)=>{var L,j;if(Ze(g,this.options)||es(O,(L=this.options.gridData)==null?void 0:L.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let v=V=>b==null?void 0:b.message.includes(V),y=b&&b instanceof wr,w=v(Sy),S=b&&(v(ia)||v(ap)||w&&!e.retryOnInfraErrors),x=!!v(ap)&&!!this.testRunTimeout,B=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||w)&&e.retryOnInfraErrors,G=S&&e.hasMoreTimeoutRetries()&&!x,E=e.hasMoreRetries()&&!y&&!S,k=!g.success&&(E||G||B);try{let V=e.retryKey;g.testRetryKey=V;let K=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,k,K),await this.runTestCleanup(),k){if(G&&await e.startNewTimeoutRetry(),B){ft.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:b});let z=(j=this.options.projectData)==null?void 0:j.projectId,re=e.testResultId,ge=e.testId;await la(z,re,ge,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return E&&!B&&!G&&await e.startNewRetry(),ft.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:S,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await p(k)}t(this.id,...r);return}catch(V){if(V instanceof tr)return;ft.error("failed to process test result",{error:V}),t(this.id,...r);return}},n=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
215
|
+
Please make sure the CLI has stable access to the internet. ${el()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:b,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:v,TIMEOUT_ERROR:y,SAUCELABS_APP_IS_NOT_INSTALLED:w}=dl,x=(g instanceof Error?g.message:g).slice(0,1e3);if(x.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),x.includes(vy)||x.includes(y))return{errorType:Br,reason:"timeout while getting device"};if(x.includes(ia)||x.includes(ap)){if(!this.testRunTimeout)return{errorType:Br,reason:"Test timeout reached!"};let _=ca.default.duration({milliseconds:this.testRunTimeout});return{errorType:Br,reason:`Test timeout reached (timeout: ${Kn(_)})`}}return x.includes(T)||x.includes(w)?{errorType:na,reason:"app doesn't exist on device"}:x.includes(v)?{errorType:na,reason:"app never started, check app permission or app activity"}:x.includes(b)?{errorType:na,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:na,reason:x}},a=(g,b)=>{let T=this.options.mode===J.APPIUM?"device":"browser";if(!b&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:eI,reason:n()};let y=(g instanceof Error?g.message:g).slice(0,1e3);if(y.includes(vy))return{errorType:Br,reason:`Test couldn't get ${T}`};if(y.includes(Sy))return{errorType:Br,reason:"Test couldn't be started"};if(g instanceof wr&&g.type){if(g.type===cp)return{errorType:cp,reason:`Test couldn't get ${T} from grid - ${y}`};if(g.type===Xt)return{errorType:Xt,reason:`Failed to create new session - ${y}`}}return y.includes(ia)?this.testRunTimeout?{errorType:Br,reason:`Test timeout reached (timeout: ${Kn(ca.default.duration({milliseconds:this.testRunTimeout}))})`}:{errorType:Br,reason:"Test timeout reached: test is too long"}:"type"in g&&g.type===tI?{errorType:Xt,reason:`Session terminated, this is often caused to connection
|
|
216
|
+
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:"type"in g&&g.type==="KEEP_ALIVE_FAILED"?{errorType:Xt,reason:"Test terminated due to repeated keep alive failures. The browser may have become unresponsive or the test environment may be unstable."}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:Xt,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:Xt,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:Xt,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:Xt,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:rI,reason:y}},c=async g=>{var w;let b=await Zc();!b&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(n()),ft.warn("error on run",{err:g});let T=(w=this.userData)==null?void 0:w.projectId,{errorType:v,reason:y}=this.options.mode===J.APPIUM?o(g):a(g,b);la(T,this.testResultId,this.testId,{status:ri.COMPLETED,success:!1,reason:y,errorType:v,testRetryKey:e.retryKey,setupStepResult:{status:ri.COMPLETED,success:!1,reason:y,errorType:v}},e.remoteRunId).catch(S=>ft.error("Failed to update test result after test failed",{error:S})),await i(sI(this.testId,this.testName,this.testResultId,y),g)},l=async g=>{var w;let b=this.testId,T=this.testResultId,v=(w=this.userData)==null?void 0:w.projectId,y=this.branch;if(!b||!T||!v||!y)return ft.warn("Test failed. Not enough data to recover results via API",{err:g}),c(g);try{let S=await Fr(b,T,v,y);if(ft.warn("Test failed. Got results via API",{err:g,testResult:Ey.default.omit(S,iI),resultId:T}),S&&S.status===ri.COMPLETED&&!g.message.includes(ia))return await i(S);throw g}catch(S){return S!==g&&ft.error("Failed to fetch test results from server",{testId:b,resultId:T,projectId:v,branch:y,err:S}),c(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===J.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),p=async g=>{try{await Promise.all([!m&&ks.joinToRemoteStep(this.testResultId),!d&&Bt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==J.APPIUM&&e.validateRunConfig();let b=await this.runTest(e,this.customExtensionLocalLocation,g);await i(b),M("After onRunComplete"),t(this.id,...r)}catch(b){await l(b),t(this.id,...r)}finally{m||ks.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,p()}}});var xy,Ry,Os,lp=I(()=>{"use strict";U();xy=R(require("p-retry"));U();W();Q();Ry=A("window-utils"),Os=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(n,o){let a=document.elementFromPoint(n,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:i}=await this.driver.executeJS(r,e,t);return i}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(i=3)=>{try{await this.driver.url(e)}catch(n){let o=n.message.includes("method IWebBrowser2::Navigate2() failed");if(n.seleniumStack&&o&&i>0)return Ry.warn("selenium navigation failed. retrying to navigate",{err:n}),await ie(1500),r(i-1);throw!n.seleniumStack&&o&&Ry.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:n}),n}};return Promise.race([r(),ie(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ie(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,i=document.documentElement,n=Math.max(r.scrollHeight,r.offsetHeight,i.clientHeight,i.scrollHeight,i.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,i.clientWidth,i.scrollWidth,i.offsetWidth);return{height:n,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ie(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&!r.href.startsWith("res://ieframe.dll/http_404.htm")&&!r.href.startsWith("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")}if(!(await this.driver.executeJS(e)).value)throw new Ot("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,xy.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var up,_s,pp=I(()=>{"use strict";W();up=A("cookies-utils"),_s=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw up.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw up.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw up.error("failed to remove cookie",{err:t}),t}}}});var dp,ua,Cy=I(()=>{"use strict";dp=R(require("p-retry")),ua=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),i=()=>Promise.all([r,this.driver.takeScreenshot()]),[n,o]=await(0,dp.default)(i,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:n}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,i=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),n=()=>Promise.all([i,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,dp.default)(n,{retries:t,minTimeout:r,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function nI(s){let{loadImage:e}=await dt("canvas"),t=Buffer.from(s,"base64");return await e(t)}async function pa(s){let e=await nI(s);return{width:e.width,height:e.height}}async function Ay(s,e){let{createCanvas:t,Image:r}=await dt("canvas"),i=t(e.width,e.height),n=i.getContext("2d"),o=new r;return o.src=`data:image/png;base64,${s}`,await new Promise((a,c)=>{o.onload=()=>a(),o.onerror=c}),n.drawImage(o,e.left,e.top,e.width,e.height,0,0,e.width,e.height),i.toDataURL("image/png")}async function Py(s,e){let t="image/png",{createCanvas:r,Image:i}=await dt("canvas"),n=r(s.width,s.height),o=n.getContext("2d");for(let c of e){let l=c.image.match(/^data:([^;]*);base64,(.*)$/),d=l[1],m=l[2],p=new i;p.src=`data:${d};base64,${m}`,await new Promise((f,h)=>{p.onload=()=>f(),p.onerror=h}),o.drawImage(p,c.position.left,c.position.top,c.size.width,c.size.height)}return n.toDataURL(t)}var mp=I(()=>{"use strict";Mi()});async function ky(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let i=t.match(/^data:[^;]*;base64,(.*)$/);if(!i)throw new Error("Image is not in base64 format");let n=s.offset||{top:0,left:0};if(n.top*=r,n.left*=r,!s.elementRect)return oI.warn("missing elementRect",_y.omit(s,"image")),{};let{elementRect:o}=s,a=o.left*r+n.left*r,c=o.top*r+n.top*r,l=o.width*r,d=o.height*r;a<0&&(l+=a,l=Math.max(l,0),a=0),c<0&&(d+=c,d=Math.max(d,0),c=0);let{width:m,height:p}=await pa(i[1]);if(a+l>m&&(l=m-a),c+d>p&&(d=p-c),d<=0||l<=0)throw new fp("height or width is equal or lower than zero");return{elementImage:await Ay(i[1],{left:a,top:c,width:l,height:d})}}function aI(s,e){return Py(s,e)}async function cI(){}async function lI(s){function e(n){let o=s[n];return typeof o=="string"&&o.startsWith("data")}async function t(n){let o=await cI(s[n]);return{key:n,url:o}}let r=await ne(Object.keys(s).filter(e),t),i=Object.fromEntries(r.map(n=>[n.key,n.url]));return Object.assign(s,i)}function Oy(s,e){return e||=1,s||={left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var _y,oI,fp,da,Ly=I(()=>{"use strict";_y=R(require("lodash"));U();mp();W();oI=A("image-capture-utils"),fp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};da=class{constructor(e,t,r){this.windowUtils=t;this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),r=await ky(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Oy(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return lI({screenImage:t.image,absoluteScreenHighlight:Oy(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,i=()=>ie(250),n=!!e;async function o(p,f){n?await t.scrollToPositionWithoutAnimation(p):await t.scrollToPosition(p),await i();let h=await r.takeScreenshot(),g=await ky({elementRect:f},h);return{position:{left:p.x+f.left,top:p.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(p){let f=[];for(let h of p){let g=await o(h.scrollPos,h.cropData);f.push(g)}return f}function c(p,f){let h=Math.max(p.width,f.width),g=f.width,b=Math.max(p.height,f.height),T=f.height,v=Array.from({length:Math.ceil(h/g)},(w,S)=>({scrollX:Math.min(S*g,h-g),cropX:S*g-Math.min(S*g,h-g),cropW:g-(S*g-Math.min(S*g,h-g))})),y=Array.from({length:Math.ceil(b/T)},(w,S)=>({scrollY:Math.min(S*T,b-T),cropY:S*T-Math.min(S*T,b-T),cropH:T-(S*T-Math.min(S*T,b-T))}));return v.flatMap(w=>y.map(S=>({scrollPos:{x:w.scrollX,y:S.scrollY},cropData:{top:S.cropY,left:w.cropX,width:w.cropW,height:S.cropH}})))}async function l(p,f){let h=await t.getCurrentScrollPosition(),g=c(p,f),b=await a(g);return await t.scrollToPosition(h),aI(p,b)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(d,m)}}});var Dy,Ny,ma,fa,My=I(()=>{"use strict";Dy=R(require("p-retry")),Ny=R(require("semver"));U();W();lp();Cy();Ly();Se();ma=A("tab-service"),fa=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let i=this.getTabInfo(e,r);return`tabId=${r}, url=${i.url}, order=${i.order}, isMain=${i.isMain}, openerStepId=${i.openerStepId}, isClosed=${i.isClosed}, currentUrl: ${i.currentUrl}, lastUpdatedUrl: ${i.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,i){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),ma.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,i)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,i,n={}){let o=await this.getTabDetails(t,e,n),a=ce();function c(l){return n.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!l.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:c(this),openerStepId:i},a}async addTab(e,t,r,i,n={}){let o=await this.buildTabInfo(e,t,r,i,n),a=new Os(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new da(t,a,new ua(t,this.driver,{takeScreenshots:n.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),i=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(i.length===1)return this._utils[i[0].infoId];let n=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return n.length>0?this._utils[n[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let i=r.filter(n=>n===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&i.length===1)}singleExactMatchForParts(e,t,r,i){let{urlUtils:n}=ee(),o=n.urlBreaker(e.url||e.currentUrl),a=n.urlBreaker(t.url||t.currentUrl),c=i(o),l=i(a),d=r.map(m=>n.urlBreaker(m)).map(m=>i(m)).filter(m=>m===c);return c===l&&d.length===1}isSameTab(e,t,r){let{tabMatcher:i}=ee();if(i){let l=this.getAllTabInfos(e),d=Object.keys(l).map(m=>l[m]);return i.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let n=this.getAllTabInfos(e),o=Object.keys(n).map(l=>n[l].url);if(this.exactUrlMatch(t,r,o))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,o,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let i=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[i.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){return!!this.getMainTabId(e)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let i=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof i=="number"&&i>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let i=Promise.resolve("unknown");r.checkForMainTab&&(i=this.driver.executeJS("return window.__isMainTestimTab").then(n=>n.value));try{let[n,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),i]);return{title:n,url:o,isMainTab:a}}catch(n){ma.error("failed to get url or title",{err:n})}}catch(i){ma.error("failed to switch to tab",{tabId:e,err:i})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ie(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){ma.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let n=await this.waitForTabToOpen(e);await this.addNewTab(e,n,this.pendingTabs[e]),this.addFrameHandler(n),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,Dy.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=Ny.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,i=r&&e.parameterValues.some(n=>n.type==="locate"&&!n.frameLocators);return t&&(!r||i)}async getTabIdByTabInfo(e,t){var c,l;let{tabMatcher:r,commonConstants:i}=ee();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:i.stepResult.INVALID_TEST_VERSION});if((c=t.useCurrentTab)!=null&&c.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let n=(l=t.tabInfo)==null?void 0:l.openerStepId;await this.waitToPendingTabs(e,n),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(p=>d.message.toLowerCase().includes(p)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var gp,ga,hp=I(()=>{"use strict";gp=class{select(){return console.log(`
|
|
217
217
|
internal error - cant use port selector in selenium!!!!
|
|
218
|
-
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},
|
|
219
|
-
const getLocatedElement = ${
|
|
218
|
+
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},ga=new gp});var sn,ha,ya=I(()=>{"use strict";pp();U();Se();sn={8:"\uE008",9:"\uE004",13:"\uE007",27:"\uE00C",33:"\uE00E",34:"\uE00F",35:"\uE010",36:"\uE011",45:"\uE016",112:"\uE031",113:"\uE032",114:"\uE033",115:"\uE034",116:"\uE035",117:"\uE036",118:"\uE037",119:"\uE038",120:"\uE039",121:"\uE03A",122:"\uE03B",123:"\uE03C"},ha=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=ci;this.getLinksFromUnescapeHTML=li;this.cookieUtils=new _s(this.driver)}get sessionPlayerInit(){return ee()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:i}=this.sessionPlayerInit,n=i.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-n.x,y:e.y-n.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:i}=await this.driver.executeJS(`return (function() { ${r} })();`);return i}}});function Uy(s){class e{constructor(r,i){this.frameManager=r;this.LocateElementPlayer=i;this._cache={}}cacheResults(r,i){this._cache[r]=i}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let i=Fy(r.seleniumFrameElement);i&&this.cacheResults(i,r.frameLocateResultUrl)}}async foundFrameCallback(r,i,n){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:c}=ee();if(c.isEmptyResult(a)){let p="got empty result in frame result, not rejected from locate element player";throw uI.error(p),new Error(p)}let l=await s.switchToLocatedFrame(a);if(!l.value)throw new Error("Element not found");let d=Fy(l.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:i.tabInfo,tabId:i.tabId,testimFrameId:n,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${n}`,seleniumFrameElement:l.value,frameLocateResultUrl:m}}async locate(r,i,n,o,a,c){let l=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${i}`;let d=await l.locate(r,n,r.targetId);d.isVisible=!0;let m=await l.handleLocateResult(d,c,r).catch(()=>{throw new Error("")}),{locatedElement:p}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(p)).value||{top:0,left:0};m.frameOffset={top:n.frameOffset.top+h.top,left:n.frameOffset.left+h.left},l.addFrameDataToContext&&l.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,i,n,o){let a=O.flags.enableFrameSwitchOptimization.isEnabled(),l=n.playback.resultsHandler.resultsByChronologicOrder.at(-1),m=l&&l.stepId===r.id&&l.results.length>1;if(a&&!m&&this.currentFrameHandler){let b=i.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(b>-1){let T=i.slice(b+1),v=0;for(let y of T)v++,this.currentFrameHandler=await this.locate(y,v,this.currentFrameHandler,n,o,r);return this.currentFrameHandler}}let p=await o.getTopFrameHandler();p.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===p?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=p;let h=0,g=p;for(let b of i)h++,g=await this.locate(b,h,g,n,o,r);return g}}return e}var uI,pI,Fy,By=I(()=>{"use strict";W();pe();Se();Gr();uI=A("frame-locator"),pI="ELEMENT",Fy=s=>s?s[pI]||s[Qt]:null});var ba,yp=I(()=>{"use strict";le();ba=()=>{try{if(Qd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var H,fe=I(()=>{"use strict";Se();H=class{constructor(e,t,r,i={},n=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=i;this.stepActionUtils=n;this.locateElementPlayer=o;this.exportsTest=a;this.frameId=0}get driver(){var e;return(e=this.context.project.defaults)!=null&&e.ignoreVisibilityForExisting&&!this.stepActionUtils.driver.getIgnoreVisibility()&&this.stepActionUtils.driver.setIgnoreVisibility(!0),this.stepActionUtils.driver}get sessionPlayerInit(){return ee()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(){try{return{success:!0,...await this.performAction()}}catch(e){let t=e==null?void 0:e.message,r=e==null?void 0:e.displayMessage;return{success:!1,reason:t,exception:e,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${t}`,error:r||t}}}}}});function mI(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:O.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?O.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function fI(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);if(!t.value)throw new Error("Element not found");e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t){let i=new jy.DOMParser().parseFromString("<html><body></body></html>","text/html");return i.body.outerHTML=e,Object.assign(i,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,i,n,o,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:d,positionUtils:m}=ee();if(mI(i,d,m,s))return s.isVisible(e.seleniumElement);if(s.getIgnoreVisibility())return{visible:!0,invisibleReason:"visibility is ignored"};if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||c.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(i.clickOffset,r)].filter(Boolean),g=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,i),b;try{b=await s.execute(`return ${g}`)}catch(S){throw jr.error("failed to execute getVisibilityCode",{err:S}),S}let{value:T}=b||{},v=T.elementVisibilityInfo||dI,[y,w]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(v,i,w,y,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=ee();await s.execute(r(t))}}}var jy,jr,dI,nn,$y=I(()=>{"use strict";fe();W();pe();Se();jy=require("linkedom"),jr=A("locate-step-action"),dI={opacity:1,clientRects:{}};nn=class extends H{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return fI(e)}static getFrameIdByTestimFrameId(){throw jr.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw jr.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw jr.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw jr.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw jr.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw jr.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Wy={};q(Wy,{scroll:()=>gI});var gI,Vy=I(()=>{"use strict";gI=function(s,e,t,r,i,n,o,a){function c(v,y){if(!y)return{success:!1};elementScrollTo(y,v.x,v.y);let w=y.scrollLeft,S=y.scrollTop;return{success:Math.abs(S-v.y)<1&&Math.abs(w-v.x)<1,actualX:w,actualY:S}}function l(v,y){if(!t)return{x:i,y:n};let w=getLocatedElement(y);if(r&&!w)return{x:v.scrollWidth,y:v.scrollHeight};if(!w)throw new Error("could not find target element");let S=w.getBoundingClientRect(),x=0,_=0,B=Math.max(window.innerHeight-(S.height+10),0),G=Math.max(window.innerWidth-(S.width+10),0);return x=a?v.scrollTop+S.top-Math.min(n,B):v.scrollTop,_=o?v.scrollLeft+S.left-Math.min(i,G):v.scrollLeft,{x:Math.round(_),y:Math.round(x)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let p={top:m.scrollTop,left:m.scrollLeft},f=l(m,e),h=c(f,m);d&&!document.scrollingElement&&!h.success&&p.top===m.scrollTop&&p.left===m.scrollLeft&&(m=document.body,f=l(m,e),h=c(f,m));let g=h.actualX,b=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let v=T.getBoundingClientRect();g=v.left,b=v.top}return{success:h.success,actualX:g,actualY:b}}});var Ta,Gy=I(()=>{"use strict";fe();Ta=class extends H{getFailureString(e,t,r,i,n){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${n}, x: ${i})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${n}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${i}`),o}async scroll(e,t,r){let{codeSnippets:i,commonConstants:{stepResult:n}}=this.sessionPlayerInit,o=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),c=this.driver.isFirefox()?function(m,p,f){m.scrollTo(p,f)}:function(m,p,f){m.scrollTop=f,m.scrollLeft=p},{scroll:l}=await Promise.resolve().then(()=>(Vy(),Wy)),d=`
|
|
219
|
+
const getLocatedElement = ${i.getLocatedElementCode};
|
|
220
220
|
const elementScrollTo = ${c.toString()};
|
|
221
221
|
const scroll = ${l.toString()};
|
|
222
222
|
return scroll.apply(null, arguments)
|
|
223
|
-
`;try{let m=await this.driver.executeJS(d,s,e??void 0,!!t.isScrollToElement,!!t.isDynamicScroll,a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:p,actualX:f,actualY:h}=m.value;return p?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,s=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,s):this.scrollOnElement(t,s)}}});var Yy,Qy=I(()=>{"use strict";Yy=function(r){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let s={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(r.fromLocatedElement),i=getLocatedElement(r.toLocatedElement);if(!n)throw new Error("from element not found");if(!i)throw new Error("to element not found");let o=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:s}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var Zy,eb=I(()=>{"use strict";Zy=function(r,e){let t=typeof MouseEvent=="function",s=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(E){e({status:"done",result:E,success:!0})}function a(E){E||={},e({status:"failed",result:E,success:!1,keep:!0})}function c(E){return E!=null&&E.toLowerCase?(E=E.toLowerCase(),E==="text"?"text/plain":E==="url"?"text/uri-list":E):E}function l(){try{return new DataTransfer}catch{return{data:{},setData(k,L){i[c(k)]=L},getData(k){return i[c(k)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],p=d.concat(["drop","dragenter","dragover"]);function f(E){let k=E;for(;k&&k!==document.documentElement;){if(k.draggable)return k;k=k.parentElement}return null}function h(E,k,L){let j=k.element,{dispatchDragEventsOnClosestDraggable:V}=L;if(d.includes(E.type)&&V){if(!j&&k.lastDraggedElement)return k.lastDraggedElement;let K=f(j);if(K)return k.lastDraggedElement=K,K}return j}function g(E,k,L){function j(ge,ze,P){return P>ge&&P<ze}let V=E.pointerPosition||{};if(k)return{x:V.originX||0,y:V.originY||0};let K=L.getBoundingClientRect(),z=V.originX&&j(K.left,K.left+K.width,V.originX)?V.originX:K.left+K.width/2,re=V.originY&&j(K.top,K.top+K.height,V.originY)?V.originY:K.top+K.height/2;return{x:z,y:re}}function b(E,k,L){let j=(k==null?void 0:k.modifiers)||{},V=g(E,L.isDrag,L.element),K=(k==null?void 0:k.button)||0,z=E.event;return m.includes(z)?v(z,j,V.x,V.y,K):p.includes(z)?w(z,j,V.x,V.y):y(z,j,V.x,V.y,K)}function T(E,k,L){return{screenX:0,screenY:0,clientX:k,clientY:L,ctrlKey:!!E.ctrl,altKey:!!E.alt,shiftKey:!!E.shift,metaKey:!!E.meta,bubbles:!0,cancelable:!0,composed:!0}}function v(E,k,L,j,V){if(n){let z=T(k,L,j);return z.pointerType="mouse",z.isPrimary=!0,new window.PointerEvent(E,z)}let K=document.createEvent("PointerEvent");return K.initPointerEvent(E,!0,!0,document.defaultView,1,0,0,L,j,!!k.ctrl,!!k.alt,!!k.shift,!!k.meta,V,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),K}function y(E,k,L,j,V){let K=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return K.initMouseEvent(E,!0,!0,document.defaultView,1,0,0,L,j,!!k.ctrl,!!k.alt,!!k.shift,!!k.meta,V,document.body?document.body.parentNode:document.documentElement),K}function w(E,k,L,j){if(E==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!s){let z=document.createEvent("CustomEvent");return z.initCustomEvent(E,!0,!0,null),Object.assign(z,{dataTransfer:window.TSTA.dataTransfer}),z}let V=T(k,L,j),K=new window.DragEvent(E,V);return Object.defineProperties(K,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),K}function S(E,k,L){let j=h(E,k,L);j==null||j.dispatchEvent(E)}function x(E,k){function L(){return E.event==="click"&&k.isDrag&&!k.allEventsOnSameElement}return L()}function _(E,k,L){if(L){let j=Math.min(L.timeStamp-k.timeStamp,40);setTimeout(()=>{B(E)},j)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function B(E){let k,L=E.events[E.eventIndex],j=E.events[++E.eventIndex];try{E.element=getLocatedElement(L.locatedElement),k=b(L,r,E)}catch(V){return a(`exception in get event in drag step:${V.message}`)}if(x(L,E))return _(E,L,j);if(k)try{S(k,E,L)}catch(V){return a(`exception in executeEvent in drag step:${V.message}`)}else return a(`cannot execute event ${L.event}`);_(E,L,j)}let G={eventIndex:0,allEventsOnSameElement:r.allEventsOnSameElement,events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement};setTimeout(()=>{try{B(G)}catch(E){a(E)}},0)}});var tb={};q(tb,{doClick:()=>xI});var xI,rb=I(()=>{"use strict";xI=(r,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function s(y,w){var _;function S(B){function G(){return i(B).find(L=>[...L.classList||[]].includes("Select-control"))}function E(){let L=G();return L?L.querySelector("input"):null}let k=E();k==null||k.focus()}let x=(_=y.quirks)==null?void 0:_.isReactSelect;w.type==="mousedown"&&x&&S(y.element)}function n(y,w){var x;let S=(x=y.quirks)==null?void 0:x.isCKEditorFrame;w.type==="click"&&S&&document.body.focus()}function i(y){let w=[];for(;y!=null&&y.parentNode;)w.push(y),y=y.parentNode;return w}function o(y){let w={status:"done",result:y,success:!0,...v.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(w)}function a(y){y||="",e({status:"failed",result:y,success:!1})}function c(y){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),y.dispatchEvent(w)}function l(y){let w={},S=y.getBoundingClientRect(),x=S.left+S.width/2,_=S.top+S.height/2,E=f("mousemove",w,x,_,0);y.dispatchEvent(E)}function d(y,w){function S(E,k,L){return L>E&&L<k}let x=y.pointerPosition||{},_=w.getBoundingClientRect(),B=x.originX&&S(_.left,_.left+_.width,x.originX)?x.originX:_.left+_.width/2,G=x.originY&&S(_.top,_.top+_.height,x.originY)?x.originY:_.top+_.height/2;return{x:B,y:G}}function m(y,w,S){return{screenX:0,screenY:0,clientX:w,clientY:S,ctrlKey:!!y.ctrl,altKey:!!y.alt,shiftKey:!!y.shift,metaKey:!!y.meta,bubbles:!0,cancelable:!0,composed:!0}}function p(y,w,S,x){if(!window.PointerEvent)return;let _=m(w,S,x);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(y,_)}function f(y,w,S,x,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(y,!0,!0,document.defaultView,1,0,0,S,x,!!w.ctrl,!!w.alt,!!w.shift,!!w.meta,_,document.body?document.body.parentNode:document.documentElement),B}function h(y,w){let S=["pointerup","pointerdown","pointermove"],x=w.modifiers||{},_=d(y,w.element),B=w.button||0,G=y.event;return S.includes(G)?p(G,x,_.x,_.y):f(G,x,_.x,_.y,B)}function g(){var w;let y=document.activeElement;for(;(w=y.shadowRoot)!=null&&w.activeElement;)y=y.shadowRoot.activeElement;return y}function b(y){y.events.map(w=>{try{return h(w,y)}catch{return}}).filter(Boolean).forEach(w=>{y.element.dispatchEvent(w),s(y,w),n(y,w)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let v={element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,quirks:r.quirks,modifiers:r.modifiers,button:r.button};if(!v.element){a("element not found");return}c(v.element),l(v.element);try{b(v);let y=g(),w=v.quirks,S=w==null?void 0:w.isReactSelect,x=w==null?void 0:w.isCKEditorFrame;!S&&!x&&dispatchFocus(r.elementToFocusLocatedElement,y),o()}catch(y){a(y.toString())}}});var sb={};q(sb,{doDragPath:()=>CI});var CI,nb=I(()=>{"use strict";CI=function(r,e){let t=typeof Event=="function",s=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(y){e({status:"done",result:y,success:!0})}function o(y){y||="",e({status:"failed",result:y,success:!1})}function a(y){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),y.dispatchEvent(w)}function c(y){let w={},S=y.getBoundingClientRect(),x=S.left+S.width/2,_=S.top+S.height/2,E=p("mousemove",w,x,_,0);y.dispatchEvent(E)}function l(y,w){function S(E,k,L){return L>E&&L<k}let x=y.pointerPosition||{};if(v.isDrag)return{x:x.originX||0,y:x.originY||0};let _=w.getBoundingClientRect(),B=x.originX&&S(_.left,_.left+_.width,x.originX)?x.originX:_.left+_.width/2,G=x.originY&&S(_.top,_.top+_.height,x.originY)?x.originY:_.top+_.height/2;return{x:B,y:G}}function d(y,w,S){return{screenX:0,screenY:0,clientX:w,clientY:S,ctrlKey:!!y.ctrl,altKey:!!y.alt,shiftKey:!!y.shift,metaKey:!!y.meta,bubbles:!0,cancelable:!0,composed:!0}}function m(y,w,S,x,_){if(s){let G=d(w,S,x);return G.pointerType="mouse",G.isPrimary=!0,new window.PointerEvent(y,G)}let B=document.createEvent("PointerEvent");return B.initPointerEvent(y,!0,!0,document.defaultView,1,0,0,S,x,!!w.ctrl,!!w.alt,!!w.shift,!!w.meta,_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),B}function p(y,w,S,x,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(y,!0,!0,document.defaultView,1,0,0,S,x,!!w.ctrl,!!w.alt,!!w.shift,!!w.meta,_,document.body?document.body.parentNode:document.documentElement),B}function f(y,w){let S=["pointerup","pointerdown","pointermove"],x=w.modifiers||{},_=l(y,w.element),B=w.button||0,G=y.event;return S.includes(G)?m(G,x,_.x,_.y,B):p(G,x,_.x,_.y,B)}function h(y,w){function S(){return y.event==="click"&&w.isDrag&&!w.allEventsOnSameElement}return S()}function g(y,w,S){try{let x=f(w.events[y],w);h(x,w)||w.element.dispatchEvent(x)}catch{}if(y+1===w.events.length)S();else{let x=Math.min(w.events[y+1].timeStamp-w.events[y].timeStamp,n);setTimeout(()=>{g(y+1,w,S)},x)}}function b(y,w){g(0,y,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w()})}let v={eventIndex:0,element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,quirks:r.quirks,isDoubleClick:r.isDoubleClick,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement,allEventsOnSameElement:r.allEventsOnSameElement};if(!v.element){o("element not found");return}a(v.element),c(v.element),b(v,()=>{i()})}});var ai,va,ib=I(()=>{"use strict";ai=R(require("lodash"));fe();Qy();ue();eb();va=class extends H{getDnDRectsAndOffsets(e,t,s,n){let i=this.stepActionUtils.getClickOffset(s,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,s=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:s.isRoot,locatedElement:s.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(rb(),tb)),Promise.resolve().then(()=>(Kn(),zn))]),l=`
|
|
223
|
+
`;try{let m=await this.driver.executeJS(d,r,e??void 0,!!t.isScrollToElement,!!t.isDynamicScroll,a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:n.SCROLL_ACTION_FAILURE,success:!1};let{success:p,actualX:f,actualY:h}=m.value;return p?{success:!0}:{errorType:n.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:n.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var Hy,qy=I(()=>{"use strict";Hy=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},i=getLocatedElement(s.fromLocatedElement),n=getLocatedElement(s.toLocatedElement);if(!i)throw new Error("from element not found");if(!n)throw new Error("to element not found");let o=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};o(i,"dragstart"),o(n,"drop"),o(i,"dragend")}});var zy,Ky=I(()=>{"use strict";zy=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",i=typeof PointerEvent=="function",n={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(E){e({status:"done",result:E,success:!0})}function a(E){E||={},e({status:"failed",result:E,success:!1,keep:!0})}function c(E){return E!=null&&E.toLowerCase?(E=E.toLowerCase(),E==="text"?"text/plain":E==="url"?"text/uri-list":E):E}function l(){try{return new DataTransfer}catch{return{data:{},setData(k,L){n[c(k)]=L},getData(k){return n[c(k)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],p=d.concat(["drop","dragenter","dragover"]);function f(E){let k=E;for(;k&&k!==document.documentElement;){if(k.draggable)return k;k=k.parentElement}return null}function h(E,k,L){let j=k.element,{dispatchDragEventsOnClosestDraggable:V}=L;if(d.includes(E.type)&&V){if(!j&&k.lastDraggedElement)return k.lastDraggedElement;let K=f(j);if(K)return k.lastDraggedElement=K,K}return j}function g(E,k,L){function j(ge,qe,P){return P>ge&&P<qe}let V=E.pointerPosition||{};if(k)return{x:V.originX||0,y:V.originY||0};let K=L.getBoundingClientRect(),z=V.originX&&j(K.left,K.left+K.width,V.originX)?V.originX:K.left+K.width/2,re=V.originY&&j(K.top,K.top+K.height,V.originY)?V.originY:K.top+K.height/2;return{x:z,y:re}}function b(E,k,L){let j=(k==null?void 0:k.modifiers)||{},V=g(E,L.isDrag,L.element),K=(k==null?void 0:k.button)||0,z=E.event;return m.includes(z)?v(z,j,V.x,V.y,K):p.includes(z)?w(z,j,V.x,V.y):y(z,j,V.x,V.y,K)}function T(E,k,L){return{screenX:0,screenY:0,clientX:k,clientY:L,ctrlKey:!!E.ctrl,altKey:!!E.alt,shiftKey:!!E.shift,metaKey:!!E.meta,bubbles:!0,cancelable:!0,composed:!0}}function v(E,k,L,j,V){if(i){let z=T(k,L,j);return z.pointerType="mouse",z.isPrimary=!0,new window.PointerEvent(E,z)}let K=document.createEvent("PointerEvent");return K.initPointerEvent(E,!0,!0,document.defaultView,1,0,0,L,j,!!k.ctrl,!!k.alt,!!k.shift,!!k.meta,V,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),K}function y(E,k,L,j,V){let K=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return K.initMouseEvent(E,!0,!0,document.defaultView,1,0,0,L,j,!!k.ctrl,!!k.alt,!!k.shift,!!k.meta,V,document.body?document.body.parentNode:document.documentElement),K}function w(E,k,L,j){if(E==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let z=document.createEvent("CustomEvent");return z.initCustomEvent(E,!0,!0,null),Object.assign(z,{dataTransfer:window.TSTA.dataTransfer}),z}let V=T(k,L,j),K=new window.DragEvent(E,V);return Object.defineProperties(K,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),K}function S(E,k,L){let j=h(E,k,L);j==null||j.dispatchEvent(E)}function x(E,k){function L(){return E.event==="click"&&k.isDrag&&!k.allEventsOnSameElement}return L()}function _(E,k,L){if(L){let j=Math.min(L.timeStamp-k.timeStamp,40);setTimeout(()=>{B(E)},j)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function B(E){let k,L=E.events[E.eventIndex],j=E.events[++E.eventIndex];try{E.element=getLocatedElement(L.locatedElement),k=b(L,s,E)}catch(V){return a(`exception in get event in drag step:${V.message}`)}if(x(L,E))return _(E,L,j);if(k)try{S(k,E,L)}catch(V){return a(`exception in executeEvent in drag step:${V.message}`)}else return a(`cannot execute event ${L.event}`);_(E,L,j)}let G={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{B(G)}catch(E){a(E)}},0)}});var Jy={};q(Jy,{doClick:()=>hI});var hI,Xy=I(()=>{"use strict";hI=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(y,w){var _;function S(B){function G(){return n(B).find(L=>[...L.classList||[]].includes("Select-control"))}function E(){let L=G();return L?L.querySelector("input"):null}let k=E();k==null||k.focus()}let x=(_=y.quirks)==null?void 0:_.isReactSelect;w.type==="mousedown"&&x&&S(y.element)}function i(y,w){var x;let S=(x=y.quirks)==null?void 0:x.isCKEditorFrame;w.type==="click"&&S&&document.body.focus()}function n(y){let w=[];for(;y!=null&&y.parentNode;)w.push(y),y=y.parentNode;return w}function o(y){let w={status:"done",result:y,success:!0,...v.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(w)}function a(y){y||="",e({status:"failed",result:y,success:!1})}function c(y){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),y.dispatchEvent(w)}function l(y){let w={},S=y.getBoundingClientRect(),x=S.left+S.width/2,_=S.top+S.height/2,E=f("mousemove",w,x,_,0);y.dispatchEvent(E)}function d(y,w){function S(E,k,L){return L>E&&L<k}let x=y.pointerPosition||{},_=w.getBoundingClientRect(),B=x.originX&&S(_.left,_.left+_.width,x.originX)?x.originX:_.left+_.width/2,G=x.originY&&S(_.top,_.top+_.height,x.originY)?x.originY:_.top+_.height/2;return{x:B,y:G}}function m(y,w,S){return{screenX:0,screenY:0,clientX:w,clientY:S,ctrlKey:!!y.ctrl,altKey:!!y.alt,shiftKey:!!y.shift,metaKey:!!y.meta,bubbles:!0,cancelable:!0,composed:!0}}function p(y,w,S,x){if(!window.PointerEvent)return;let _=m(w,S,x);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(y,_)}function f(y,w,S,x,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(y,!0,!0,document.defaultView,1,0,0,S,x,!!w.ctrl,!!w.alt,!!w.shift,!!w.meta,_,document.body?document.body.parentNode:document.documentElement),B}function h(y,w){let S=["pointerup","pointerdown","pointermove"],x=w.modifiers||{},_=d(y,w.element),B=w.button||0,G=y.event;return S.includes(G)?p(G,x,_.x,_.y):f(G,x,_.x,_.y,B)}function g(){var w;let y=document.activeElement;for(;(w=y.shadowRoot)!=null&&w.activeElement;)y=y.shadowRoot.activeElement;return y}function b(y){y.events.map(w=>{try{return h(w,y)}catch{return}}).filter(Boolean).forEach(w=>{y.element.dispatchEvent(w),r(y,w),i(y,w)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let v={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!v.element){a("element not found");return}c(v.element),l(v.element);try{b(v);let y=g(),w=v.quirks,S=w==null?void 0:w.isReactSelect,x=w==null?void 0:w.isCKEditorFrame;!S&&!x&&dispatchFocus(s.elementToFocusLocatedElement,y),o()}catch(y){a(y.toString())}}});var Yy={};q(Yy,{doDragPath:()=>yI});var yI,Qy=I(()=>{"use strict";yI=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",i=40;window.__unloadNavigator=n,window.addEventListener("unload",window.__unloadNavigator);function n(y){e({status:"done",result:y,success:!0})}function o(y){y||="",e({status:"failed",result:y,success:!1})}function a(y){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),y.dispatchEvent(w)}function c(y){let w={},S=y.getBoundingClientRect(),x=S.left+S.width/2,_=S.top+S.height/2,E=p("mousemove",w,x,_,0);y.dispatchEvent(E)}function l(y,w){function S(E,k,L){return L>E&&L<k}let x=y.pointerPosition||{};if(v.isDrag)return{x:x.originX||0,y:x.originY||0};let _=w.getBoundingClientRect(),B=x.originX&&S(_.left,_.left+_.width,x.originX)?x.originX:_.left+_.width/2,G=x.originY&&S(_.top,_.top+_.height,x.originY)?x.originY:_.top+_.height/2;return{x:B,y:G}}function d(y,w,S){return{screenX:0,screenY:0,clientX:w,clientY:S,ctrlKey:!!y.ctrl,altKey:!!y.alt,shiftKey:!!y.shift,metaKey:!!y.meta,bubbles:!0,cancelable:!0,composed:!0}}function m(y,w,S,x,_){if(r){let G=d(w,S,x);return G.pointerType="mouse",G.isPrimary=!0,new window.PointerEvent(y,G)}let B=document.createEvent("PointerEvent");return B.initPointerEvent(y,!0,!0,document.defaultView,1,0,0,S,x,!!w.ctrl,!!w.alt,!!w.shift,!!w.meta,_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),B}function p(y,w,S,x,_){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(y,!0,!0,document.defaultView,1,0,0,S,x,!!w.ctrl,!!w.alt,!!w.shift,!!w.meta,_,document.body?document.body.parentNode:document.documentElement),B}function f(y,w){let S=["pointerup","pointerdown","pointermove"],x=w.modifiers||{},_=l(y,w.element),B=w.button||0,G=y.event;return S.includes(G)?m(G,x,_.x,_.y,B):p(G,x,_.x,_.y,B)}function h(y,w){function S(){return y.event==="click"&&w.isDrag&&!w.allEventsOnSameElement}return S()}function g(y,w,S){try{let x=f(w.events[y],w);h(x,w)||w.element.dispatchEvent(x)}catch{}if(y+1===w.events.length)S();else{let x=Math.min(w.events[y+1].timeStamp-w.events[y].timeStamp,i);setTimeout(()=>{g(y+1,w,S)},x)}}function b(y,w){g(0,y,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w()})}let v={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!v.element){o("element not found");return}a(v.element),c(v.element),b(v,()=>{n()})}});var on,wa,Zy=I(()=>{"use strict";on=R(require("lodash"));fe();qy();pe();Ky();wa=class extends H{getDnDRectsAndOffsets(e,t,r,i){let n=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(i,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:n.x,fromY:n.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),i=t.data.timeToPlayStep+3e3,n=e.events;if(!(n!=null&&n.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:n,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(Xy(),Jy)),Promise.resolve().then(()=>(qi(),Hi))]),l=`
|
|
224
224
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
225
225
|
var dispatchFocus = ${c.toString()};
|
|
226
226
|
var doClick = ${a.toString()};
|
|
227
227
|
var eventData = arguments[0];
|
|
228
228
|
var done = arguments[1];
|
|
229
229
|
return doClick.call(null, eventData, done);
|
|
230
|
-
`;try{return(d=(await this.driver.executeCodeAsync(l,
|
|
230
|
+
`;try{return(d=(await this.driver.executeCodeAsync(l,i,o)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var c;let e=(c=this.step.events[0])==null?void 0:c.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,i=this.isWithinBounds(r.left,r.left+r.width,e.originX),n=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=i?0:r.left+r.width/2-e.originX,a=n?0:r.top+r.height/2-e.originY;return{xOffset:o,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=on.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:i}=this.step,n=e.find(l=>["mousedown","pointerdown"].includes(l.event));if(n){let l=e.indexOf(n);e.splice(l,0,this.generateEventOfType(n,"mouseover"))}let{recordPointerMoveEvents:o=!1}=this.context.project.defaults||{},a=e.find(l=>l.event==="mouseup")||o&&e.find(l=>l.event==="pointerup"),c=Number(on.findLastIndex(e,l=>l.event==="mousemove")||o&&on.findLastIndex(e,l=>l.event==="pointermove"));a&&c>0&&!t&&e.splice(c+1,0,this.generateEventOfType(a,"mouseover")),r&&!i&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var d,m;let{step:e,context:t}=this,r=this.getTarget(),i=t.data.timeToPlayStep+3e3;if(!((d=e.events)!=null&&d.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let n=e.events,o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:n,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(Qy(),Yy)),Promise.resolve().then(()=>(qi(),Hi))]),l=`
|
|
231
231
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
232
232
|
var dispatchFocus = ${c.toString()};
|
|
233
233
|
var doDragPath = ${a.toString()};
|
|
234
234
|
return doDragPath.apply(null, arguments);
|
|
235
|
-
`;try{return(m=(await this.driver.executeCodeAsync(l,
|
|
235
|
+
`;try{return(m=(await this.driver.executeCodeAsync(l,i,o)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(p){return{success:!1,reason:p.message,exception:p}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset:i,rect:n}=e,o={frameOffset:{x:n.left-i.left,y:n.top-i.top},rect:i,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,i)};if(O.flags.skipFileInputClicks.isEnabled()&&e.tagName==="INPUT"&&(e.elementSymbol.includes('type="file"')||e.elementSymbol.includes("type='file'")||e.elementSymbol.includes("type=file")))return{keep:!0,success:"skipped",reason:"Clicking on input type=file is disabled"};if(this.step.isDoubleClick){let d={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,d,o)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(O.flags.usePortedHtml5DragDrop.isEnabled()){let h=this.generateHTML5DragEventSequence(),g=this.context.data.timeToPlayStep+3e3,b=this.getTarget(),T={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:h,eventData:{modifiers:this.step.modifiers,button:this.step.button},quirks:this.step.quirks,isDrag:this.step.isDrag,useRecordedMousedown:this.step.useRecordedMousedown,allEventsOnSameElement:this.step.allEventsOnSameElement,elementToFocusLocatedElement:b.elementToFocusLocatedElement,trackActiveElement:this.step.trackActiveElement,locatedElement:b.locatedElement,isRoot:b.isRoot},v=`
|
|
236
236
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
237
|
-
var dnd = ${
|
|
237
|
+
var dnd = ${zy.toString()};
|
|
238
238
|
var eventData = arguments[0];
|
|
239
239
|
var done = arguments[1];
|
|
240
240
|
return dnd.call(null, eventData, done);
|
|
241
241
|
`;return this.driver.executeCodeAsync(v,g,T)}let p=`
|
|
242
242
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
243
|
-
var dnd = ${
|
|
243
|
+
var dnd = ${Hy.toString()};
|
|
244
244
|
var eventData = arguments[0];
|
|
245
245
|
return dnd.call(null, eventData);
|
|
246
|
-
`,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(p,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(m)}return this.dragPathJs()}let c=this.driver.isSafari()&&this.step.button===2,l=this.driver.isSafari()&&e.tagName==="SELECT";return l?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!l&&(!this.step.nativeEvents||c)?this.clickJs():this.step.button===2?this.driver.rightClick(
|
|
247
|
-
var getLocatedElement = ${
|
|
246
|
+
`,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(p,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(m)}return this.dragPathJs()}let c=this.driver.isSafari()&&this.step.button===2,l=this.driver.isSafari()&&e.tagName==="SELECT";return l?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!l&&(!this.step.nativeEvents||c)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(i=>["dragend","drop"].includes(i.event)),r=e[t-1];if(!r||r.event!=="dragover"){let i={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,i)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let i=n=>n.fireOnTarget||["drop","dragenter"].includes(n.event);return e.forEach(n=>Object.assign(n,{locatedElement:i(n)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(i=>i.event!=="mousemove"&&i.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(i=>Object.assign(i,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var an,eb=I(()=>{"use strict";fe();an=class extends H{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:i,commonConstants:n}}=this,o=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(o),{evaluatedText:c}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return i.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:n.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:n.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var tb,bI,va,rb=I(()=>{"use strict";tb=R(require("lodash"));fe();W();bI=A("evaluate-expression-step-action"),va=class extends H{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:i}=this;try{bI.info("runner running incoming params evaluation");let n=t.incomingParams||{};tb.isEmpty(n)&&(n=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,i));let o=["context",...n.as.functionParameters],a=[t,...n.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,o.concat([l]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(n){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:n.toString()},success:!1}}}}});var sb={};q(sb,{setText:()=>TI});var TI,ib=I(()=>{"use strict";TI=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),i={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){re()},window.addEventListener("unload",window.__unloadNavigator);let n=new Set(["keydown","keyup","keypress"]),o=15;function a(P){try{if(!t)return;let D=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return P.eventData&&(D.data=P.eventData.data),D}catch{}}function c(P){try{let D=document.createEvent("TextEvent");D.data=P.eventData.data;let $=1,X=P.eventData.locale||"en-US";return D.initTextEvent("textInput",!0,!0,window,P.eventData.data,$,X),D}catch{}}function l(P){return a(P)||c(P)}function d(P,D,$){try{return new KeyboardEvent(P,{bubbles:!0,cancelable:!0,location:D.location||0,key:D.key||"",ctrlKey:!!$.ctrl,shiftKey:!!$.shift,altKey:!!$.alt,metaKey:!!$.meta})}catch{}}function m(P,D,$){try{let X=document.createEvent("KeyboardEvent");return X.initKeyEvent(P,!0,!0,null,!!$.ctrl,!!$.alt,!!$.shift,!!$.meta,D.key||"",0),X}catch{}}function p(P,D,$){try{let X=document.createEvent("Events");return X.initEvent(P,!0,!0),Object.assign(X,{altKey:!!$.alt,ctrlKey:!!$.ctrl,metaKey:!!$.meta,shiftKey:!!$.shift,keyCode:D.key||""}),X}catch{}}function f(P,D,$){return d(P,D,$)||m(P,D,$)||p(P,D,$)}function h(P){if(!n.has(P.event))return null;let D=P.eventData,$=D.modifiers||{},X=f(P.event,D,$);return Object.defineProperties(X,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(X,{_keyCode_:D.keyCode,_charCode_:D.charCode||0}),X}function g(P){return P.event==="textInput"?l(P):h(P)}function b(P,D){return(()=>{var X;return P.event==="textInput"&&!((X=D.quirks)!=null&&X.isAuth0Form)})()}function T(P,D){return P.event==="keyup"&&D.event==="keydown"?o:0}function v(P,D){let $=T(P,D);return Math.min(D.timeStamp-P.timeStamp,$)}function y(P){let D=Object.getOwnPropertyDescriptor(P,"value");if(!D)return;let $=P.value;P.value=`${$}#`,D.configurable&&delete P.value,P.value=$;let X=document.createEvent("HTMLEvents");X.initEvent("input",!0,!1),P.dispatchEvent(X),Object.defineProperty(P,"value",D)}function w(P){if(j(P.element))try{if(y(P.element),t)P.element.dispatchEvent(new Event("change"));else{let D=document.createEvent("HTMLEvents");D.initEvent("change",!1,!0),P.element.dispatchEvent(D)}}catch{}}function S(P,D,$){$?setTimeout(()=>{L(P)},v(D,$)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w(P),re())}function x(P,D){return(P==="change"||P==="blur")&&D.element.tagName==="OPTION"}function _(P,D,$){return x(P.type,D)?D.element.parentElement:$.locatedElement?getLocatedElement($.locatedElement):D.element}function B(P,D){let $=P.firstChild,X;for(;$;){if($.nodeType===3){if(D.offset--<=0)return $}else if($.nodeType===1&&(X=B($,D),X))return X;$=$.nextSibling}return null}function G(P,D){if(!(!P||!D)){if(!isNaN(D.start))Object.assign(P,{selectionStart:D.start,selectionEnd:D.end});else if(!isNaN(D.nodeOffset)){let $;if(P.firstChild?$=B(P,{offset:D.nodeOffset}):$=P,$){let X=window.getSelection(),Le=document.createRange();try{X.removeAllRanges(),Le.setStart($,D.textOffset),Le.setEnd($,D.textOffset),X.addRange(Le)}catch{}}}}}function E(P,D){return P==="submit"&&!!D.action}function k(P,D,$){if(D.isFocusable&&D.isSelectable(P)&&P.type!=="submit")try{G(D.element,$.eventData.selection)}catch{}let X=_(P,D,$);if(!X)throw new Error("could not find element");E(P.type,X)?X.submit():X.dispatchEvent(P)}function L(P){let D,$=P.events[P.eventIndex],X=P.events[++P.eventIndex];try{D=g($)}catch(Le){return ge(`exception in get event in text step:${Le.message}`)}if(b($,P))return S(P,$,X);if(D)try{k(D,P,$)}catch(Le){return ge(`exception in executeEvent in text step:${Le.message}`)}else if(P.noEventExecuter)P.noEventExecuter(P,$);else return ge(`cannot execute event ${$.event}`);S(P,$,X)}function j(P){let D=P.tagName;return D==="INPUT"||D==="TEXTAREA"}function V(P){return P.getAttribute?P.getAttribute("contenteditable")==="true":!1}function K(P,D){if(j(P.element)){P.element.value=D.eventData.text;let $=document.createEvent("Event");$.initEvent("input",!0,!1),P.element.dispatchEvent($)}else P.isContentEditable&&(P.element.innerHTML=D.eventData.text)}function z(){var D;let P=document.activeElement;for(;(D=P.shadowRoot)!=null&&D.activeElement;)P=P.shadowRoot.activeElement;return P}function re(P){let D={status:"done",result:P,success:!0,...i.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(D)}function ge(P){P||="";let D={status:"failed",result:P,success:!1,...i.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(D)}try{let P=j(i.element);i.isContentEditable=V(i.element),!P&&!i.isContentEditable&&(i.isNonTextableElemnet=!0),i.isFocusable=P||i.isContentEditable,i.isSelectable=D=>D.type!=="keyup",i.noEventExecuter=K}catch(P){ge(`exception in set text step:${P.message}`);return}let qe=z();dispatchFocus(s.elementToFocusLocatedElement,qe),L(i)}});var Sa,nb=I(()=>{"use strict";fe();U();Sa=class extends H{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Ue(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:i,sessionPlayerInit:n}=this,o=this.getTarget(),a=i.data.timeToPlayStep+3e3,{setTextDraftJs:c}=n.codeSnippets;if(o.isDraftEditor&&c)return this.driver.executeJS(c(o.locatedElement,i.stepText));if(!(e!=null&&e.length))return;let l={eventType:t,events:e,quirks:r,locatedElement:o.locatedElement,isRoot:o.isRoot,elementToFocusLocatedElement:o.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(ib(),sb)),Promise.resolve().then(()=>(qi(),Hi))]),p=`
|
|
247
|
+
var getLocatedElement = ${n.codeSnippets.getLocatedElementCode};
|
|
248
248
|
var dispatchFocus = ${m};
|
|
249
249
|
var setText = ${d.toString()};
|
|
250
250
|
var eventData = arguments[0];
|
|
251
251
|
var done = arguments[1];
|
|
252
252
|
return setText.call(null, eventData, done);
|
|
253
|
-
`;return{success:!!((h=(await this.driver.executeCodeAsync(p,a,l)).value)!=null&&h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let
|
|
253
|
+
`;return{success:!!((h=(await this.driver.executeCodeAsync(p,a,l)).value)!=null&&h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Ue(t.seleniumElement),e[r]),r<e.length-1&&await ie(this.step.delayBetweenChars||0)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Ue(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var ob={};q(ob,{runCode:()=>wI});var wI,ab=I(()=>{"use strict";wI=function(s,e){var d;function t(m,p){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(b){return b!=null&&b.toString?b.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let T={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...p};window.sessionStorage.setItem(f,JSON.stringify(T))}catch(b){let T=b.message.toLowerCase().includes("quota"),v=b.message===h;if(b.message.includes("sessionStorage")||b.message.includes("The operation is insecure")||T||v){let y=document.head.querySelector("#testim-storage-backup");y||(y=document.createElement("meta"),y.id="testim-storage-backup",document.head.append(y));let S={...JSON.parse(y.getAttribute(f)||"{}"),...p};if(y.setAttribute(f,JSON.stringify(S)),T||v)try{window.sessionStorage.removeItem(f)}catch{}return}throw b}}function r(m){return m.function?m.function.args.map(p=>p!=null&&p.locatedElement?getLocatedElement(p.locatedElement):p):m.directParams.map(p=>p.selector?document.querySelector(p.selector):p.value).concat(m.otherParams)}function i(m,p){function f(){return m.apply(null,p)}return f.prototype=m.prototype,new f}let n={},o={},a={},c=s.functionParams,l=s.transactionId;try{let m=r(s);m.push(n,o,a);let p=((d=s.function)==null?void 0:d.params)||c,h=(e||i(Function,p)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(l,{type:"promise"}),h.then(g=>{t(l,{status:"done",success:!0,result:{resultValue:g,exports:n,exportsTest:o,exportsGlobal:a}})},g=>{t(l,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:n,exportsTest:o,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:h,exports:n,exportsTest:o,exportsGlobal:a}})}catch(m){t(l,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:n,exportsTest:o,exportsGlobal:a}})}}});var Ea,cn,dr,Ia=I(()=>{"use strict";Ea=R(require("lodash"));U();fe();W();pe();cn=A("base-js-step-action"),dr=class extends H{isExceedingMaxResultSize(e,t){var r;try{let i=(r=t.project.defaults)==null?void 0:r.enforceMaximumJsResultSize,n=O.flags.maximumJsResultSize.getValue(),o=JSON.stringify(e).length>n;return i?o:(o&&cn.warn(`js result size exceeded ${n}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(e){return this.driver.executeJS(t=>{let r=`data-testim-${t}`;try{return window.sessionStorage.getItem(r)}catch(i){if(i.message.includes("sessionStorage")||i.message.includes("The operation is insecure")){let n=document.head.querySelector("#testim-storage-backup");return n?n.getAttribute(r):"{}"}throw i}},e)}constructJSFunParams(e){let t=e.incomingParams,r=["context",...t.as.functionParameters,"exports","exportsTest","exportsGlobal"],i=[e.context,...t.as.functionArguments];return r.push(e.code),i.forEach(n=>{Ea.isObject(n)&&Jn(n,"seleniumElement",Ea.isEqual)}),{function:{params:r,args:i},transactionId:e.transactionId,browser:e.browser,browserMajor:e.browserMajor}}checkStatus(e){let{context:t,stepActionUtils:r,step:{id:i=""}}=this,n=t.config.retryTimeout,o=t.data.timeToPlayStep-n,a=async()=>{let c;try{c=await this.executeGetStatus(e)}catch(m){cn.warn("failed to get js status",{err:m}),c={value:'{ "status": "exception" }'}}let l;try{l=JSON.parse((c==null?void 0:c.value)||"{}")}catch{cn.warn("non object value",{selRes:c}),l={status:"exception"}}let d=r.abortedSteps.find(m=>m.id===i);return d||(l?l.status==="done"?l:l.status==="failed"?{success:!1,shouldRetry:!0,result:l.result}:o-n<=0?Object.assign(l,{success:!1,shouldRetry:!0}):(o-=n,await ie(n),a()):{success:!0})};return a()}async executeInAut(e){let t=O.flags.experimentalPreCodeCompilation.isEnabled(),r=O.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(e),n=i.function.args.some(d=>!!(d!=null&&d.locatedElement)),o="undefined";if(t){let d=i.function.params.slice(0,-1);o=r?`async function(${d.join(",")}) {
|
|
254
254
|
${e.code}
|
|
255
255
|
};`:`function(${d.join(",")}) {
|
|
256
256
|
${e.code}
|
|
257
|
-
};`,
|
|
258
|
-
${
|
|
257
|
+
};`,i.function.params.pop()}let{codeSnippets:a}=this.sessionPlayerInit,{runCode:c}=await Promise.resolve().then(()=>(ab(),ob)),l=`
|
|
258
|
+
${n?`var getLocatedElement = ${a.getLocatedElementCode};`:";"}
|
|
259
259
|
var runCode = ${c.toString()};
|
|
260
260
|
var eventData = arguments[0];
|
|
261
261
|
var funcToRun = ${o};
|
|
262
262
|
return runCode.call(null, eventData, funcToRun);
|
|
263
|
-
`;if(!t)return this.driver.executeJS(l,
|
|
263
|
+
`;if(!t)return this.driver.executeJS(l,i);try{return await this.driver.executeJS(l,i)}catch(d){return this.handleExecutionError(d)}}codeExecDone(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants,{context:r}=this,{result:i={},tstConsoleLogs:n,nodeVersion:o,navigateToDifferentDomain:a}=e;i.exports&&(r.data.exports=i.exports);let c={nodeVersion:o,tstConsoleLogs:n,data:r.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:t.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:n},r)?{...c,success:!1,errorType:t.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...a&&{navigateToDifferentDomain:a}}}codeExecFailed(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants,{context:r}=this;if(e.type==="promise")return{data:r.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:t.JS_ASSERTION_FAILED};if(e.reason==="stopped")return{...e,errorType:t.STOPPED};let{result:i={},tstConsoleLogs:n}=e;return{tstConsoleLogs:n,data:r.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:t.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(e){return e!=null&&e.success?this.codeExecDone(e):this.codeExecFailed(e)}getTransactionId(e,t){var i;let r=e.id;return e.id||(cn.warn("step.id doesn't exist on step",{step:e,context:t}),r=t.stepResultId),"stepResultId"in t&&((i=t.stepResultId)!=null&&i.length)?r=t.stepResultId:cn.warn("stepResultId is not present in context",{step:e,context:t}),`${t.testResultId}:${r}`}async performAction(){let{step:e,context:t}=this;this.startTimestamp=Date.now();let r=await this.driver.getBrowserAndOS(),i={transactionId:this.getTransactionId(e,t),id:e.id,eventType:e.type,code:e.code,incomingParams:t.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:t.config,data:t.data},testResultId:t.testResultId,browser:r.browser,browserMajor:r.browserMajor};t.isPendingPromise||await this.executeInAut(i);let n=await this.checkStatus(i.transactionId);return this.checkCodeResponse(n)}handleExecutionError(e){throw(e==null?void 0:e.name)==="javascript error"?new Error(e.message):e}}});var Yt,cb=I(()=>{"use strict";Ia();Yt=class extends dr{isFailedResult(e){return e===!1}}});var Ls,lb=I(()=>{"use strict";Ia();Ls=class extends dr{isFailedResult(e){return!e}}});var Ra,ub=I(()=>{"use strict";fe();U();ya();Ra=class extends H{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Ue(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(sn[t]),this.setWithValueApi(e)}}});var xa,pb=I(()=>{"use strict";fe();ya();xa=class extends H{async performAction(){var n,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((n=this.step.keys)!=null&&n.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let i=r.keyCode;if(i>=32&&i<=127)t.push(r.key);else if(sn[i])t.push(sn[i]);else throw new Error(`Invalid key with keyCode ${i}.`);return await this.driver.sendKeyboardShortcut(t)}}});var db={};q(db,{selectOption:()=>vI});function vI(s,e){function t(r,i){let n=Element.prototype.matches,o=n&&isNativeFunction(n)?n:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,i))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let i=t(r,"select");return i?(i.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(o=>{let a=document.createEvent("HTMLEvents");return a.initEvent(o,!0,!1),a}).forEach(o=>{if(e){i.dispatchEvent(o);return}r.dispatchEvent(o)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var mb=I(()=>{"use strict"});var Ca,fb=I(()=>{"use strict";fe();U();pe();Ca=class extends H{async performAction(){var p,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,n=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=!!((p=this.step.element)!=null&&p.isShadowed);if(!o||o&&n>=13&&!a)try{return await this.driver.elementIdClick(Ue(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:c}=await Promise.resolve().then(()=>(mb(),db)),l=O.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
|
|
264
264
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
265
265
|
const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
|
|
266
266
|
const selectOption = ${c.toString()};
|
|
267
267
|
return selectOption.apply(null, arguments);
|
|
268
|
-
`;return(f=(await this.driver.executeJS(d,
|
|
268
|
+
`;return(f=(await this.driver.executeJS(d,r,l)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var Aa,gb=I(()=>{"use strict";fe();Aa=class extends H{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var SI,Pa,hb=I(()=>{"use strict";fe();SI=(s,e,t,r)=>({x:t,y:r,width:e,height:s,get top(){return this.y},get left(){return this.x},get right(){return this.x+this.width},get bottom(){return this.y+this.height},toJSON(){}}),Pa=class extends H{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:i}=e,{width:n,height:o}=i,a=n/2,c=o/2,l=this.step.element.clickOffset;if(l&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:p}=l;this.sessionPlayerInit.utils.isWithinTargetRect(SI(o,n,0,0),m,p)&&(a=m,c=p)}let d={frameOffset:{x:i.left-r.left,y:i.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(c)}};return await this.driver.hover(t,d),{success:!0}}}});var yb={};q(yb,{wheel:()=>EI});var EI,bb=I(()=>{"use strict";EI=function(s,e){function r(a,c){function l(h,g,b){return b>h&&b<g}let d=a.pointerPosition||{},m=c.getBoundingClientRect(),p=d.originX&&l(m.left,m.left+m.width,d.originX)?d.originX:m.left+m.width/2,f=d.originY&&l(m.top,m.top+m.height,d.originY)?d.originY:m.top+m.height/2;return{x:p,y:f}}function i(a,c,l){let d=r(a,l),m=(c==null?void 0:c.modifiers)||{},p={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:d.x,clientY:d.y,bubbles:!0,cancelable:!0,ctrl:!!m.ctrl,alt:!!m.alt,shift:!!m.shift,meta:!!m.meta};return new WheelEvent("wheel",p)}function n(a,c){if(a.length===0){e({state:"success"});return}if(!c)throw new Error("element not found");let l=a.shift(),d=i(l,s.eventData,c),m=a[0]?Math.min(a[0].timeStamp-l.timeStamp,200):200;c.dispatchEvent(d),setTimeout(()=>{n(a,c)},m)}let o=getLocatedElement(s.locatedElement);n(s.events,o)}});var ka,Tb=I(()=>{"use strict";fe();ka=class extends H{async performAction(){var m;let{step:e,context:t}=this,{events:r,modifiers:i,button:n}=e;if(!(r!=null&&r.length))return;let o={events:r,eventData:{modifiers:i,button:n},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:c}=await Promise.resolve().then(()=>(bb(),yb)),l=`
|
|
269
269
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
270
270
|
var wheel = ${c.toString()};
|
|
271
271
|
var eventData = arguments[0];
|
|
272
272
|
var done = arguments[1];
|
|
273
273
|
return wheel.call(null, eventData, done);
|
|
274
|
-
`;return{success:((m=(await this.driver.executeCodeAsync(l,a,o)).value)==null?void 0:m.state)==="success"}}}});var
|
|
274
|
+
`;return{success:((m=(await this.driver.executeCodeAsync(l,a,o)).value)==null?void 0:m.state)==="success"}}}});var wb={};q(wb,{downloadFileAndFireDropEvent:()=>II});var II,vb=I(()=>{"use strict";II=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let o=-1,a=0,c=[],l={endWithCallback:void 0,waitOn(){let d=++o;return function(m){d in c||(c[d]=m,a++,e.length===a&&l.endWithCallback(c))}},endWith(d){l.endWithCallback=d}};return l}function i(o,a,c){let l=new XMLHttpRequest;l.open("GET",o),l.responseType="blob",l.onload=function(){if(this.status>=200&&this.status<300)c({blob:l.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},l.onerror=function(){throw new Error("Failed to load blob")},l.send()}let n=r();e.forEach(o=>{i(o.url,o.name,n.waitOn())}),n.endWith(o=>{let a=createDropEvent(o);t.dispatchEvent(a)})}});var RI,Oa,Sb=I(()=>{"use strict";fe();W();pe();RI=A("drop-file-step-action"),Oa=class extends H{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:i}=this,n=this.getTarget(),o=O.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,i.fileUrls,this.stepActionUtils.testimServicesApi,o,RI),{downloadFileAndFireDropEvent:c}=await Promise.resolve().then(()=>(vb(),wb)),l=`
|
|
275
275
|
const getLocatedElement = ${e.getLocatedElementCode};
|
|
276
276
|
const createDropEvent = ${e.createDropEvent.toString()};
|
|
277
277
|
const downloadFileAndFireDropEvent = ${c.toString()};
|
|
278
278
|
return downloadFileAndFireDropEvent.apply(null, arguments)
|
|
279
|
-
`;return await this.driver.executeJS(l,
|
|
279
|
+
`;return await this.driver.executeJS(l,n.locatedElement,a)}}});function Rb(s={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
|
|
280
280
|
var input = getLocatedElement(locatedElement);
|
|
281
281
|
if(input) {
|
|
282
282
|
function parents(element, _elements) {
|
|
@@ -305,20 +305,20 @@ Please make sure the CLI has stable access to the internet. ${tl()?"(Internal: n
|
|
|
305
305
|
})
|
|
306
306
|
|
|
307
307
|
forceStyle(input, 'visibility', 'visible');
|
|
308
|
-
forceStyle(input, 'width', '${
|
|
309
|
-
forceStyle(input, 'max-width', '${
|
|
310
|
-
forceStyle(input, 'height', '${
|
|
311
|
-
forceStyle(input, 'max-height', '${
|
|
308
|
+
forceStyle(input, 'width', '${s.width}');
|
|
309
|
+
forceStyle(input, 'max-width', '${s.width}');
|
|
310
|
+
forceStyle(input, 'height', '${s.height}');
|
|
311
|
+
forceStyle(input, 'max-height', '${s.height}');
|
|
312
312
|
forceStyle(input, 'z-index', 100000000);
|
|
313
313
|
forceStyle(input, 'opacity', 1);
|
|
314
|
-
forceStyle(input, 'top', '${
|
|
315
|
-
forceStyle(input, 'left', '${
|
|
314
|
+
forceStyle(input, 'top', '${s.top}');
|
|
315
|
+
forceStyle(input, 'left', '${s.left}');
|
|
316
316
|
forceStyle(input, 'position', 'fixed');
|
|
317
317
|
forceStyle(input, 'pointer-events', 'all');
|
|
318
318
|
input.removeAttribute("disabled");
|
|
319
319
|
input.focus();
|
|
320
320
|
}
|
|
321
|
-
}`}async function
|
|
321
|
+
}`}async function CI(s,e){let t=null;try{t=(await Qc(s)).body}catch(i){if(xI.error("failed to download input-file content",{err:{message:i.message,stack:i.stack,status:i.status}}),i.response)t=i.response.body;else throw i.cause?new Error(i.message):i}let r=`${Eb.tmpdir()}/${e}`;return await Ib.promises.writeFile(r,t),r}function AI(s){return ne(s,e=>CI(e.url,e.name))}function PI(s,e){return e(s)}async function xb(s,e){let t=await AI(s),r=await ne(t,i=>PI(i,e));return Array.isArray(r)&&r.map(i=>i==null?void 0:i.value)}var Eb,Ib,xI,Cb=I(()=>{"use strict";Eb=R(require("os"));We();Ib=require("fs");U();W();xI=A("input-file-utils")});function OI(){return`async function downloadAndUpload(locatedElement, fileUrls) {
|
|
322
322
|
const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
|
|
323
323
|
const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
|
|
324
324
|
const attachTo = document.body || document.documentElement;
|
|
@@ -395,31 +395,31 @@ Please make sure the CLI has stable access to the internet. ${tl()?"(Internal: n
|
|
|
395
395
|
element.dispatchEvent(new Event("change", { bubbles: true }));
|
|
396
396
|
}
|
|
397
397
|
element.removeEventListener("change", changeFiredHandler, true);
|
|
398
|
-
}`}var La,
|
|
398
|
+
}`}var _a,La,Ab=I(()=>{"use strict";Cb();fe();W();U();pe();_a=A("input-file-step-action"),La=class extends H{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){_a.info("workaround - stepaction - move element to visible position");let i=`
|
|
399
399
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
400
|
-
var getVisibleElement = ${
|
|
400
|
+
var getVisibleElement = ${Rb(r)};
|
|
401
401
|
return getVisibleElement.apply(null, arguments);
|
|
402
|
-
`;return this.driver.executeJS(
|
|
402
|
+
`;return this.driver.executeJS(i,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(i){throw _a.error("failed to set input file in Safari recovery",{err:i}),i}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(i){let n="The element is not editable",o="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",c="element not interactable",l="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",p="is not reachable by keyboard",f=i?i.message:"";if(f===d||f.startsWith(m)||f.startsWith(n)||f.startsWith(o)||f.startsWith(a)||f.includes(p)||f.includes(c)||f.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw _a.error("failed to set input file",{err:i}),i}}async uploadFiles(t,r){for(let i of t)await this.driver.elementIdValue(Ue(r.seleniumElement),i)}async performAction(){let t=this.getTarget(),r=O.flags.overrideAzureStorageUrl.isEnabled(),i=O.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:n,context:o,step:a,stepActionUtils:c,driver:l}=this,d=await n.utils.addTokenToFileUrls(o.project.id,a.fileUrls,c.testimServicesApi,r,_a);if(d.length===0)throw new Error("No files urls to upload");if(i&&(d=await Promise.all(d.map(async({name:p,url:f})=>{let h=await Ht(f);return{name:p,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),l.isSafari()||l.isFirefox()||l.isEdgeChromium()){await this.driver.executeJS(`
|
|
403
403
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
404
|
-
const downloadAndUploadFile = ${
|
|
405
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await _b(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var Na,Ma,Nb=I(()=>{"use strict";Na=require("url");fe();Ma=class extends H{async updateBaseUrl(e){let t=new Na.URL(e),s=new Na.URL(this.context.recordedBaseUrl),n=new Na.URL(this.context.baseUrl);return t.host===s.host&&s.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var Fa,Mb=I(()=>{"use strict";fe();U();Fa=class extends H{async performAction(){await ie(this.step.durationMS||0)}}});var Ua,Fb=I(()=>{"use strict";fe();Ua=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var ui,Ub=I(()=>{"use strict";fe();ui=class extends H{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:s}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(s,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:s}=this,n={id:t.id,url:s.apiUrl,method:t.method,headers:s.apiHeaders,body:s.apiBody,timeout:s.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(s.project.type),formData:t.formData,fileUrls:s.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ba,Bb=I(()=>{"use strict";fe();Ba=class extends H{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var jb,vp,Sp,$b=I(()=>{"use strict";jb=R(require("@applitools/spec-driver-webdriverio"));Oi();Se();vp=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=em["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:s}=require("@applitools/eyes-sdk-core");this.sdk=s({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:jb.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,s,n){let{EyeSdkBuilder:i}=ee(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(s,n),o}},Sp=new vp});var Wb,Ep,pi,Vb=I(()=>{"use strict";Wb=R(require("lodash"));fe();W();$b();Ep=A("pixel-validation-step-action"),pi=class extends H{async performAction(){var d,m;let{shouldUseVisualGrid:e,applitoolsSdkConfig:t,applitoolsSdkLogger:s,testResultId:n}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},o=((m=t.batch)==null?void 0:m.id)||n,a=await Sp.getManager(e,this.context.config.applitoolsConcurrency||5,o,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},l;try{let p=await a.openEyes({driver:this.driver.client,config:t,logger:s}),h={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Wb.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),Ep.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await p.check({settings:h}),l={isApplitoolsSdkResult:!0,success:!0,eyesResults:await p.close()},Ep.info("Applitools SDK step executed successfully (selenium mode)",{projectId:this.context.projectId})}catch(p){Ep.error("Applitools SDK step failed",{err:p,info:p.info}),l={isApplitoolsSdkResult:!0,success:!1,err:p}}return await Sp.handleApplitoolsSdkResult(this.context,l,this.step)}}});var Ms,Ip=I(()=>{"use strict";ks();Q();Ra();Ms=class extends fr{async executeCliCode(){var h,g,b;let{step:e,context:t}=this,s=this.stepActionUtils.driver.isMobile;if(!((b=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:b.cliAction)&&!s)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:d}=t,m={config:t.config,data:t.data},p=t.data.timeToPlayStep,f=await Ps(i,o,a,m,c,l,d,p);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof pe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var gr,Gb=I(()=>{"use strict";Ip();gr=class extends Ms{isFailedResult(e){return e===!1}}});var ja,Hb=I(()=>{"use strict";Ip();ja=class extends Ms{isFailedResult(e){return!e}}});var $a,qb=I(()=>{"use strict";ks();fe();Q();$a=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:s,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await As(e,s,n,t,i,o),success:!0}}catch(a){return a instanceof Lt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof pe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Wr,zb=I(()=>{"use strict";fe();Wr=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var we,Kb=I(()=>{"use strict";fe();we=class extends H{async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Wa,Jb=I(()=>{"use strict";fe();Wa=class extends H{async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Va,Xb=I(()=>{"use strict";fe();Va=class extends H{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(s){return{success:!1,reason:s.reason||s.message,exception:s,shouldRetry:!1}}finally{t.releaseObjects()}}}});function WI(r,e){Object.keys(r).forEach(t=>{e.registerStepAction(t,r[t])})}function Ga(r,e){WI(VI,e),e.registerLocateStepActionUtils(oi.getUtils(r))}var VI,Rp=I(()=>{"use strict";zy();Xy();ib();ob();cb();pb();fb();gb();hb();yb();wb();vb();Sb();Rb();Ab();Db();Nb();Mb();Fb();Ub();Bb();Vb();Gb();Hb();qb();zb();Kb();Jb();Xb();VI={locate:oi,scroll:wa,mouse:va,submit:Pa,text:Ea,"special-key":xa,"user-code":Qt,"validation-code-step":Qt,"wait-for-code-step":Qt,"action-code-step":Qt,"condition-step":Ns,"skip-code-step":Ns,"element-code-step":Ns,"evaluate-expression":Sa,"text-validation":ci,"wait-for-text-validation":ci,"select-option":Aa,"drop-file":_a,"input-file":Da,hover:ka,navigation:Ma,wheel:Oa,sleep:Fa,refresh:Ua,"keyboard-shortcut-step":Ca,"api-validation":ui,"api-action":ui,"api-code-step":Qt,"extract-text":Ba,"simple-ui-verification":pi,"wait-for-simple-ui-verification":pi,"cli-validation-download-file":Wr,"cli-wait-for-download-file":Wr,"network-validation-step":Wr,"cli-validation-code-step":gr,"cli-wait-for-code-step":gr,"cli-action-code-step":gr,"cli-api-code-step":gr,"cli-condition-step":ja,"node-package":$a,"email-code-step":Qt,"cli-email-code-step":gr,"sfdc-internal-test-step":Va,"sfdc-recorded-step":Wa,"sfdc-step-login":we,"sfdc-step-loginas":we,"sfdc-step-logout":we,"sfdc-step-sobjectcreate":we,"sfdc-step-sobjectdelete":we,"sfdc-step-findrecord":we,"sfdc-step-quickaction":we,"sfdc-step-sobjectedit":we,"sfdc-step-sobjectvalidate":we,"sfdc-step-launchapp":we,"sfdc-step-wait-for-page-load":we,"sfdc-step-closeconsoletabs":we,"sfdc-step-relatedlistaction":we,"sfdc-step-permission-validation":we,"sfdc-step-convert-lead-to-opportunity":we,"sfdc-step-quotelineeditor":we,"sfdc-document-validation":Wr,"sfdc-step-flow-screen-completion":we,"sfdc-step-sobjectverifyoptions":we}});var Yb,GI,Fs,xp=I(()=>{"use strict";Yb=["simple-ui-verification","wait-for-simple-ui-verification"],GI=[...Yb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Fs=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let s=Date.now();this.currentRetryStart=s,this.lastUpdateTime=s}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let s=this.getTotalStepRunTime(e),n=GI.includes(e.stepType)?[s]:t(s);this.resetStepVariables(s,n),e.context.data.maxTotalStepTime=s}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let s=e.context.config.stepTimeout;return Yb.includes(e.stepType)&&(s=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(s=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:s}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let s=Date.now()-e.startTimestamp;return t-s}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,s=e.step.type,n=3e4;return s==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var Zb={};q(Zb,{SeleniumTestPlayer:()=>di});var Qb,HI,di,Cp=I(()=>{"use strict";U();Qb=require("@applitools/eyes-sdk-core");Xn();Q();W();fp();Wy();Tp();ba();Hy();wp();Se();Rp();xp();le();HI=A("SeleniumTestPlayer"),di=class{constructor(e,t,s,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Fs(Ta());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=n??new Nr;let d=new ya(this.driver);this.stepActionFactory=new l(d),Ga(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new ga(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Gy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ds(this.driver),FrameLocator:m,portSelector:ha,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Qb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(!!s),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var s,n;let{commonConstants:e}=ee(),t=1e3*60*2;try{await ce((s=this.driver)==null?void 0:s.end(),t)}catch(i){i instanceof pe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let s=await this.driver.getTabIds();if(!Array.isArray(s)){HI.error("addTab: driver.getTabIds() returned a non-array",{ids:s});return}let n=s.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},s=[]){let n=await this.driver.getTabIds(),i=[new URL(nt||wr).hostname].concat(s);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(c=>a.url.includes(c))){this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Pp={};q(Pp,{WorkerSelenium:()=>Ap});function zI(r){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))r.playbackManager.on(t,()=>M(`Got event ${t}`))}var Ha,qI,Ap,kp=I(()=>{"use strict";U();$e();ni();W();Ft();Yo();ae();dp();Q();Cp();Se();pt();Ha=A("worker-selenium"),qI=1e9,Ap=class extends $t{initPlayer(e){return new di(this.id,e.runParams,this.options.shouldMonitorPerformance,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,s,n){M("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,e.runMode);let{driver:i}=s;this.windowUtils=new Ls(this.id,i),s.clearSessionTabs();let{browserValue:o}=this.testRunConfig,a=e.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({projectData:this.options.projectData,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:J.SELENIUM,customCapabilities:e.customCapabilities}),M("in WorkerSelenium after driver.init"),await s.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(a,qI),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let l=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&o==="firefox",d=c.message&&c.message==="invalid argument";throw c instanceof _t||l||d?new _t(`Page '${a}' is not available`):(Ha.error("failed to navigate to page",{baseUrl:a,err:c,whitelistedPublicIp:go(),initializedFromCache:ho()}),c)}}async runTestOnce(e,t){var d;let{manifestVersion:s,localAssetService:n}=ee(),{driver:i,sessionPlayer:o}=t,a=s||"runner";Z.onWaitToTestComplete(this.id),zI(o),o.playbackManager.executionId=e.executionId,o.playbackManager.executionName=e.executionName,this.options.mode===J.SELENIUM&&o.setLightweightMode(this.options.lightweightMode),e.sfdcCredential&&o.setSfdcCredential(e.sfdcCredential),n.initialize({serverUrl:this.options.localRCASaver});let c=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(c=(await Zn(this.options))[this.testId]);let l=async()=>ce(new Promise((m,p)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:e.remoteRunId,preloadedTest:c}).catch(p)}),this.testRunTimeout,Ae.TEST_COMPLETE_TIMEOUT_MSG).catch(m=>{var p;throw m instanceof pe&&((p=o.stopPlayingOnTestTimeout)==null||p.call(o)),m}).then(async m=>{await n.drain(),m.stepsResults=null,m.resultId=this.testResultId,i.isAlive()||(Ha.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),m.gridIssues="could not validate grid is alive");let p=i.maxKeepAliveGap();p>=3e4&&(Ha.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),m.keepAliveIssue=p);let h={...m,...e.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(e,t),M("right after super.runTestOnce in workerSelenium");let m=await l();return M("right after runSeleniumTest"),m}catch(m){throw Ha.error("failed to run test once",{err:m}),m}}}});var eT,qe,KI,Op,xt,qa=I(()=>{"use strict";eT=R(require("ora"));hp();le();Ve();ye();W();ae();Se();ue();qe=A("mobile-grid-service"),KI="https://tdc.tricentis-cloud.com",Op=class{constructor(){this.gridsAppIdGetter={[N.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[N.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[N.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[N.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:s})=>e.getSauceLabsAppPath(s,t)}}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return e.type===N.TESTIM_TDC?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:s}=e;return t===N.TESTIM_TDC?`${s||_c}/${hm}/devices`:""}getHeaders(e){return{...e.type===N.TESTIM_TDC&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...e.type===N.TESTIM_TDC&&{device_id:t}}}async lockDevice(e,t){let s=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await We({url:s,headers:n,body:i})}catch(o){throw qe.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getTDCDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await ve(n,void 0,this.getHeaders(e));return this.extractTDCDeviceConnection(i,e.accessToken)}catch(i){throw qe.error("error while getting automation config for device",{error:i,deviceId:t}),i}}extractTDCDeviceConnection(e,t){let s=Object.keys(e)[0],n=e[s].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let s={};return e.type===N.TESTIM_TDC&&(s=await this.getTDCDeviceConnection(e,t)),s}getGridConnection(e){var s;if(e.type===N.TESTIM_TDC){let n=(s=e.host)!=null&&s.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===N.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if([N.BROWSERSTACK,N.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:s,projectType:n,companyId:i,gridId:o}){var a,c,l;if(t===N.TESTIM_TDC){let d=await fi({projectId:s,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}return t===N.BROWSERSTACK?((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName):t===N.SAUCELABS?e.testobject_device_name:e.device}async updateDeviceOnRemoteTestResult(e,t,s,n,i=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:p="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,b;if(f===N.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:v}=ee();b=v(t.capabilities,i)}else b=await this.getDeviceFromAppiumCapabilities(h,t,s,g,f,l,d,m,p,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await _r(l,o,a,c,"RUNNING",{device:b,...T&&{remoteResultLink:T}}),qe.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:b,remoteResultLink:T,gridType:f}),b}getOsVersion(e,t){var n;let s=e.platformVersion;return!s&&t===N.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:s}async getScaleFactorAndSize(e,t,s,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),c=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:c}}try{let{AppiumApi:o}=ee(),a=new o(t,s.sessionId,null,i),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),{width:d,height:m}=await da(c);return{scaleFactor:d/l.width,width:d,height:m}}catch(o){return qe.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,s,n,i,o,a,c,l,d){let[m,p]=await Promise.all([this.getScaleFactorAndSize(e,s,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:c,gridId:l})]),f=this.getOsVersion(e,i);return{name:p??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,s){return e.type===N.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Xs}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===N.SAUCELABS?s.testobject_test_report_url:e.type===N.TESTIM_TVC?s.replayUrl:e.type===N.TESTIM_TDC?`${KI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await ve(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,s){let{executionId:n,testId:i,testResultId:o}=s,{project:a,localTmaUrl:c}=t,l=await this.getTmaDeviceDetails(c,e);return await _r(a,n,i,o,"RUNNING",{device:l}),qe.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:l}),l}async getGridAppId({gridData:e,testRunHandler:t,projectId:s}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(O.flags.allowFixingAppIdStructure.isEnabled()&&(qe.info("fixing gridAppId structure",{gridAppId:o,projectId:s,testResultId:t.testResultId,executionId:t.executionId}),await Lp({gridAppId:o,gridId:e.gridId,projectId:s,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:s}){let n=await mi({appId:e,projectId:t});return{appUrl:`${be()}/storage${n.filePath}?access_token=${s}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,s=Math.ceil(e/1024);return t=(Math.ceil(s/(gm*60))+1)*60*1e3,Math.max(fm,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:s,gridId:n,gridType:i}){let a={[N.BROWSERSTACK]:{name:"Browserstack"},[N.TESTIM_TVC]:{name:"Mobile Virtual Grid"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let c=s||t.mobileApp,l=(0,eT.default)(`uploading app to ${a} please wait..`).start();try{qe.info(`uploading app to ${a} during test run`,{mobileApp:s,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await _p({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});return l.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw l.fail(`failed to upload app to ${a}`),qe.error(`failed to upload app to ${a}`,{error:d,mobileApp:s,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:s,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:s,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:s}){let n="",i,{executionId:o,testResultId:a}=e,{appId:c="",project:l,authData:{token:d=""}={},gridData:m={}}=t,{gridId:p="",type:f=""}=m;if(!c&&e.isAppFromDevice)return n;if(c){qe.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else qe.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:m,testRunHandler:e}),b=f===N.BROWSERSTACK||f===N.TESTIM_TVC;if(g){let T=t.projectData.type,v=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});v&&(qe.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=g),!v&&b&&(qe.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:s,projectId:l,gridId:p,gridType:f,mobileAppId:h})),!v&&!b&&qe.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&b&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:s,projectId:l,gridId:p,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:s}){let{accessToken:n,user:i,host:o,key:a,type:c,apiUrl:l}=t;if(c===N.BROWSERSTACK){let d=`${Xs}/recent_apps`,m=await this.fetchWithUserAndPasswordAuth({url:d,user:i,key:a});return Array.isArray(m)?m.some(p=>p.app_url===e):!1}if(c===N.SAUCELABS){let d=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:d,user:i,key:a})).items.some(p=>p.id===e)}if(c===N.TESTIM_TDC){let d=`${l}/${Lc}/apps`;return l||(d=`${_c}/${Lc}/apps`),(await this.fetchWithTokenAuth({url:d,accessToken:n,authType:"Bearer"})).apps.some(p=>p.app_id===e)}if(c===N.TESTIM_TVC){let d=`${ym}/versions/${e}/info`,m=t[`${s}Token`];try{return await this.fetchWithTokenAuth({url:d,accessToken:m,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(p){return p.status!==404&&qe.error("error while verifying app exists on TVC",{error:p}),!1}}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:s}){let n={Authorization:`Basic ${Buffer.from(`${t}:${s}`).toString("base64")}`};return await ve(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:s,userAgent:n}){let i={Authorization:`${s} ${t}`,...n&&{"User-Agent":n}};return await ve(e,void 0,i)}},xt=new Op});function rT({nativeAppMetadata:r,appPath:e,gridInfo:t}){if(!r&&!e||!r)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!r.id&&!r.activity&&!r.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!JI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function XI({deviceUdid:r,gridInfo:e,testRunConfig:t}){let{staticAllocation:s}=(t==null?void 0:t.mobile)||{};if(e.type!==N.TESTIM_TDC)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!r&&!(s!=null&&s.deviceUdid))throw Error("missing device udid or test run config is not static");if(!r&&(s!=null&&s.deviceUdid)&&s.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function YI(r){let{testName:e,executionId:t,testResultId:s,customTag:n}=r,i=[{executionId:t},{testResultId:s}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function QI(r,e,t,s){let{fullReset:n,setNoReset:i,skipLoadBalancer:o}=e,c=r===N.TESTIM_TDC&&O.flags.enableBatchTDC.isEnabled(),l=O.flags.increaseTDCRequestTimeout.isEnabled();return{"tdc:options":{"tdc:capture.video":!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{"tdc:capture.network":!1},...o&&{"tdc:controlLock":!0},"tdc:retryNewSessionFailure":!1,"tdc:sessionTags":YI(t),"tdc:enableBatch":c,...!n&&{"appium:noReset":i},...l&&{"tdc:newCommandTimeout":600,"appium:newCommandTimeout":600},...s}}}function za(r){return"id"in r?r.id:r.packageName}function ZI(r){return{"tdc:app.id":r}}function eR({projectType:r,sessionCaps:e,options:t,nativeAppMetadata:s,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":n},l=n==null?void 0:n.startsWith("http");n&&!l&&(c=ZI(n));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(r){case"ios":return{"appium:options":{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...s&&{"appium:bundleId":za(s)},...n&&c}};case"android":return{"appium:options":{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...s&&{"appium:appPackage":za(s),"appium:appActivity":s.activity??".*"},...n&&c}};default:throw Error(`unsupported mobile project ${r}`)}}function Us({projectType:r,sessionCaps:e,nativeAppMetadata:t,appPath:s,androidActivityWait:n,shouldRunInEnhancedMode:i}){let{"appium:options":o,...a}=e;switch(r){case"ios":return{"appium:options":{platformName:"iOS",autoAcceptAlerts:!0,automationName:i?"WaldoTestim":"XCUITest",fullReset:!0,...t&&{bundleId:za(t)},...s&&{app:s},...o},...a};case"android":return{"appium:options":{platformName:"Android",autoGrantPermissions:!0,automationName:i?"WaldoTestim":"UiAutomator2",...n&&{appWaitActivity:`${n}, *`},...t&&{appPackage:za(t),appActivity:t.activity??".*"},...s&&{app:s},...o},...a};default:throw Error(`unsupported mobile project ${r}`)}}function sT({projectType:r,nativeAppMetadata:e,appPath:t,androidActivityWait:s,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a,customCapabilities:c}){let l=QI(o.type,i,n,c);return eR({projectType:r,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:s,shouldRunInEnhancedMode:a})}function Np({osVersion:r,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:s}=e;return r||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:s!=null&&s.osVersionRegex?s==null?void 0:s.osVersionRegex:".*")}function Mp({deviceName:r,mobileConfig:e,projectType:t,gridType:s}){let{staticAllocation:n,dynamicAllocation:i}=e;return r||(n!=null&&n.deviceName?n.deviceName:i!=null&&i.deviceNameRegex?i.deviceNameRegex:t==="ios"&&s===N.BROWSERSTACK?"iPhone.*":".*")}function tR(r,e){let{androidToken:t,iosToken:s}=r,n=e==="ios";if(!t&&!s)throw Error("missing access token for testim virtual cloud");if(n&&!s)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?s:t}function nT(r,e,t){return r?Object.entries(r).reduce((s,[n,i])=>{if(e(n)){if(!t)return s[n]=i,s;let o=n.replace(t,"");s[o]=i}return s},{}):{}}function rR(r){return nT(r,e=>e.startsWith("browserstack."),"browserstack.")}function sR(r){return nT(r,e=>!e.startsWith("browserstack."))}function iT(r){return!r||!oT(r)?"2.0.0":r}function oT(r){return r.split(".")[0]==="2"||r.includes("appium2")||["latest","stable"].includes(r)}function aT({osVersion:r,projectType:e,appiumVersion:t,isBrowserStack:s=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=s&&i.test(r),c=e==="android"&&(n.test(r)||a),l=e==="ios"&&o.test(r),d=c||l;if(t){let m=oT(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${r}, forcing appium 2 for current session.`),!0):m}return d}function tT(r,e){let t={};return Object.entries(r).forEach(([s,n])=>{let i=s.startsWith(e)?s:`${e}${s}`;t[i]=n}),t}async function nR(r){let{projectType:e,nativeAppMetadata:t,appPath:s,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c,shouldRunInEnhancedMode:l,customCapabilities:d}=r,{osVersion:m,deviceName:p}=i,f=(c==null?void 0:c.mobile)||{},{type:h}=o,g=tR(o,e),b=await fi({gridId:o.gridId,projectType:e,projectId:i.project,companyId:i.company.companyId}),T=b==null?void 0:b.find(({udid:x})=>{var _;return((_=f.staticAllocation)==null?void 0:_.deviceUdid)===x}),v=(T==null?void 0:T.osVersion)??Np({osVersion:m,mobileConfig:f}),y=(T==null?void 0:T.name)??Mp({deviceName:p,mobileConfig:f,projectType:e,gridType:h}),w=Ke(i.editorUrl,i.project,a.testId,a.testResultId,a.branch),S={"waldo:device":y,"waldo:os_version":v,"waldo:displayName":`${a.testName}-${a.executionId}-${a.testResultId}`,"waldo:externalUrl":w,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:token":g,...d};return S["waldo:options"]||(S["waldo:options"]={}),S["waldo:options"].token||(S["waldo:options"].token=g),Us({projectType:e,sessionCaps:S,nativeAppMetadata:t,appPath:s,androidActivityWait:n,shouldRunInEnhancedMode:l})}function iR({projectType:r,nativeAppMetadata:e,appPath:t,androidActivityWait:s,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,customCapabilities:c}){let{osVersion:l,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:p}=i,f=Np({osVersion:l,mobileConfig:m}),h=Mp({deviceName:d,mobileConfig:m,projectType:r,gridType:p}),g=(0,Ct.omit)({...n.saucelabs},["automationName","platformName"]),b={...g["sauce:options"]};delete g["sauce:options"];let T={...c==null?void 0:c["sauce:options"]},v=(0,Ct.omit)(c,"sauce:options"),y=b.appiumVersion||T.appiumVersion,w=g.platformVersion||v.platformVersion||f;if(aT({osVersion:w,projectType:r,appiumVersion:y})){let x={debug:!0,networkLogs:!0},_={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:iT(y??"stable"),deviceName:h,tags:Object.values(o)},B={platformName:r==="android"?"Android":"iOS",browserName:"","appium:options":{platformVersion:f,deviceName:h,...g,...v},"sauce:options":{...x,..._,...(0,Ct.omit)(b,"appiumVersion"),...(0,Ct.omit)(T,"appiumVersion")}};return Us({projectType:r,sessionCaps:B,nativeAppMetadata:e,appPath:t,androidActivityWait:s})}let S={"sauce:options":{"saucelabs.user":i.user,"saucelabs.key":i.key,tags:Object.values(o),name:o.testResultId,build:o.executionId},platformName:r==="android"?"Android":"iOS",browserName:"","appium:platformVersion":f,"appium:deviceName":h,"appium:device":h,...g,...b,...v,...T};return Us({projectType:r,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:s})}function oR({projectData:r,projectType:e,nativeAppMetadata:t,appPath:s,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c,customCapabilities:l}){let{osVersion:d,deviceName:m}=i,p=(c==null?void 0:c.mobile)||{},{type:f}=o,h=Np({osVersion:d,mobileConfig:p}),g=Mp({deviceName:m,mobileConfig:p,projectType:e,gridType:f}),b=rR(i.browserstack),T=(0,Ct.omit)(sR(i.browserstack),["automationName","platformName","project","build","name"]),v={...l==null?void 0:l["bstack:options"]},y=(0,Ct.omit)(l,"bstack:options"),w=b.appiumVersion||v.appiumVersion,S=T.platformVersion||y.platformVersion||h,x=O.flags.enableAppium2BrowserStack.isEnabled(),_={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${r.name} - ${r.projectId}`,sessionName:`${a.testName} - ${a.testId}`};if(x||aT({osVersion:S,projectType:e,isBrowserStack:!0,appiumVersion:w})){let G={..._,userName:o.user,accessKey:o.key,appiumVersion:x?"2.0.1":iT(w),debug:!0,networkLogs:!0},E={"appium:options":{platformVersion:h,deviceName:g,...T,...y},"bstack:options":{...G,...(0,Ct.omit)(b,"appiumVersion"),...(0,Ct.omit)(v,"appiumVersion")}};return Us({projectType:e,sessionCaps:E,nativeAppMetadata:t,appPath:s,androidActivityWait:n})}let B={..._,os_version:T.platformVersion||h,device:T.deviceName||g,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...T,...tT(b,"browserstack."),...y,...tT(v,"browserstack.")};return Us({projectType:e,sessionCaps:B,nativeAppMetadata:t,appPath:s,androidActivityWait:n})}async function aR(r){if(N.TESTIM_TDC===r.gridInfo.type)return sT(r);if(N.TESTIM_TVC===r.gridInfo.type)return await nR(r);if(N.SAUCELABS===r.gridInfo.type)return iR(r);if(N.BROWSERSTACK===r.gridInfo.type)return oR(r);throw new Error(`unsupported grid type ${r.gridInfo.type}`)}function cR(r,e){var l,d;let{staticAllocation:t,dynamicAllocation:s,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=r,c={};return n==="dynamic"&&(!i&&((l=s==null?void 0:s.selector)!=null&&l.manufacturer)&&(c.manufacturer=s.selector.manufacturer),!o&&((d=s==null?void 0:s.selector)!=null&&d.osVersion)&&(c.os_version=s.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),i&&(c.manufacturer=i),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function cT(r){let{gridInfo:e,nativeAppMetadata:t,options:s,appPath:n,testRunConfig:i}=r,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);rT({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=xt.getGridConnection(e),c=await aR(r);if(e.type===N.TESTIM_TDC){let b=cR(s,i==null?void 0:i.mobile);if(!(0,Ct.isEmpty)(b)){let T=Object.entries(b).map(([v,y])=>y.split(",").map(w=>w===".*"||w==="="?"":`${v}:${w}`).join(",")).join(" ").trim();c["tdc:selector"]=T}}let l=e.type===N.TESTIM_TVC?{alwaysMatch:c}:c,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,p=(0,Dp.default)("2m"),f=(0,Dp.default)("12m"),h=Er(O.flags.appiumConnectionRetryCount.getValue(),m),g=Er(O.flags.appiumConnectionRequestTimeout.getValue(),p);return d&&g<f&&(g=f),{...a,desiredCapabilities:c,connectionRetryTimeout:g,capabilities:l,connectionRetryCount:h,logLevel:s.appiumLogLevel}}async function lT(r){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:s,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:c}=r,{deviceUdid:l}=n;rT({nativeAppMetadata:s,appPath:i,gridInfo:t}),XI({deviceUdid:l,gridInfo:t,testRunConfig:c});let d=l||((g=(h=c.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await xt.getGridDirectConnection(t,d),f=sT({projectType:e,nativeAppMetadata:s,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return d&&(f["appium:options"]||={},f["appium:options"]["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function uT(r){let{projectType:e,nativeAppMetadata:t,appPath:s,androidActivityWait:n,customCapabilities:i}=r,o={...i,dontStopAppOnReset:!0,fullReset:!1},a=Us({projectType:e,sessionCaps:o,nativeAppMetadata:t,appPath:s,androidActivityWait:n});return e==="ios"&&delete a["appium:options"].app,a}function pT(r){var t,s;let e={...r};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(s=e.capabilities["sauce:options"])==null||delete s.key,delete e.capabilities.key,delete e.capabilities.user,e}var Dp,Ct,JI,Fp=I(()=>{"use strict";Dp=R(require("ms"));ue();ae();qa();Ct=require("lodash");U();ye();JI=[N.BROWSERSTACK,N.SAUCELABS,N.TESTIM_TDC,N.TESTIM_TVC]});var Ka,mT=I(()=>{"use strict";Ka=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Ja,fT=I(()=>{"use strict";U();Ja=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=dn;this.getLinksFromUnescapeHTML=mn}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Up,Xa,gT=I(()=>{"use strict";W();Up=A("mobile-frame-locator-mock"),Xa=class{foundFrameCallback(){return Up.info("foundFrameCallback-mock invoked"),{}}locate(){return Up.info("locate-mock invoked"),{}}async findFrame(){return Up.info("findFrame-mock invoked"),{}}}});var lR,yT,hT,Bs,Bp=I(()=>{"use strict";lR=R(require("webdriverio")),yT=require("@applitools/eyes-sdk-core");mT();Tp();W();fT();wp();Se();Rp();gT();xp();hT=A("appium-test-player"),Bs=class{constructor(e,t,s,n=lR,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=ee(),m=new Ja(this.driver);this.stepActionFactory=new l(m),Ga(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Fs(Ta()),this.sessionPlayer=new a(e,{tabService:new Ka,cookieUtils:void 0,FrameLocator:Xa,portSelector:ha,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:yT.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(!!s),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:s}={},appiumApi:n}=e,i={executionId:t,testResultId:s,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),hT.info("appium session deleted",{...i}))}catch(o){hT.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=ee();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function uR(r){return await ve(`${r}/api/status`)}async function bT(r,e){return await ve(`${r}/api/devices/${e}/status`)}async function TT(r){if((await uR(r)).fsmState!=="Ready")throw new Error("TMA is not ready")}var wT=I(()=>{"use strict";Ve()});var vT={};q(vT,{WorkerLocalTma:()=>Vp});var Vr,jp,$p,Wp,Vp,ST=I(()=>{"use strict";Ve();Fp();ni();U();W();Ft();Bp();Se();wT();qa();Vr=A("worker-appium"),jp=class extends Error{},$p=class extends Error{},Wp=class extends Error{},Vp=class extends $t{constructor(){super(...arguments);this.baseDevicePath=(t,s)=>`${t}/api/devices/${s}`}initPlayer(t){return new Bs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:s}=ee(),{DOMParser:n}=await import("linkedom"),i=new s(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,s,n,i){var S;if(Z.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:c}=this.options;await TT(o);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=n,p=c.type,f=this.options.appId;if(f){let{mobileApp:x}=await xt.getMobileAppDataByAppId({appId:f,projectId:l,token:d});t.nativeApp=x}let h=p==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,b=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:v,version:y},w]=await Promise.all([this.getAppStateFromDevice(o,a,T),bT(o,a)]).catch(x=>{throw this.handleDeviceNotFoundError(x),x});if(Vr.info("device status and app state",{deviceStatus:w,appInstalled:v,version:y,executionId:this.executionId,testResultId:this.testResultId}),!v&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!v&&b&&(await this.installApp(o,a,b),Vr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let x={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(S=this.options.projectData)==null?void 0:S.name}-${this.options.project}`},_=uT({projectType:p,nativeAppMetadata:g,appPath:b,androidActivityWait:h,sessionTags:x,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,customCapabilities:t.customCapabilities}),B={capabilities:{udid:a,..._}};Vr.info("requesting new appium session from TMA",{tmaSessionSettings:B,executionId:this.executionId,testResultId:this.testResultId});let G=await this.requestNewAppiumSessionFromTma(o,B,g);this.sessionData=G;let E=await m.attach({sessionId:G.sessionId,capabilities:_});this.device=await xt.updateTmaDeviceDetails(a,this.options,t),Vr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:E.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:E.capabilities})}catch(x){throw Vr.error("failed to start application",{err:x}),x}}async requestNewAppiumSessionFromTma(t,s,n){var i,o;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:s,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new Wp(c):a}}async getAppStateFromDevice(t,s,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,s)}/${i}`,c=(await ve(o)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,s,n){var i,o;try{let a=await qt(n);await nn(`${this.baseDevicePath(t,s)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new $p(l,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let s=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof s=="string"&&(s!=null&&s.startsWith("Ensure that the requested device")))throw new jp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,s){let{manifestVersion:n,localAssetService:i}=ee(),{sessionPlayer:o}=s,a=n||"runner";Z.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device,nativeApp:t.nativeApp},await this.initAndGetAppiumAPI(s),i.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((m,p)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(p)});return await i.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw Vr.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,s),await c()}catch(l){throw Vr.error("failed to run test once",{err:l}),l}}}});var IT={};q(IT,{WorkerAppium:()=>Gp});var ET,Gr,Gp,RT=I(()=>{"use strict";U();Fp();ET=require("linkedom");ni();W();Ft();Bp();Se();qa();ae();ys();Gr=A("worker-appium"),Gp=class extends $t{initPlayer(e){return new Bs(this.id,e.runParams,this.options.shouldMonitorPerformance,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,s,n){let i=this.options.projectData.type,o=(i==="android"||i==="ios")&&await e.isTestRecordedWithEnhancedMode();if(n.type!==N.TESTIM_TVC&&o)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Z.onGetSession(this.id,this.testName,e.runMode);let{driver:a}=s,c=await xt.getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),l=i==="android"?e.androidActivityWait:null,d=e.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch},p={projectData:this.options.projectData,projectType:i,nativeAppMetadata:d,appPath:c,androidActivityWait:l,sessionTags:m,gridInfo:n,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:o,customCapabilities:e.customCapabilities},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await xt.lockDevice(n,this.options.deviceUdid),f=await lT(p)):f=await cT(p),Gr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:pT(f)}),f.headers={"User-Agent":this.getUserAgentString()};let h=this.getServerAddressFromGrid();this.activeSession=await a.remote(f),this.device=await xt.updateDeviceOnRemoteTestResult(e,this.activeSession,h,this.options,o);let g=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),Gr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Gr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}startKeepAlive(e){let{errors:t}=ee(),s=async()=>{try{await e.getOrientation()}catch(n){Gr.error("failed to keep appium session alive",{err:n}),t!=null&&t.AppiumSessionTerminatedError&&n instanceof t.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(s,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(e){try{this.options.slotService==="redis"&&jg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:e},this.id)}catch(t){Gr.error("failed to update slot data",{err:t})}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:s,type:n}=this.options.gridData;return n===N.TESTIM_TDC?`https://${e}:${t}/v0/${s}/wd/hub`:`https://${e}:${t}/wd/hub`}getDirectAddressConnection(){let{protocol:e,hostname:t,port:s,path:n}=this.activeSession.options;if(e&&t&&s&&n)return`${e}://${t}:${s}${n}`}async runTestOnce(e,t){var p,f,h;let{manifestVersion:s,AppiumApi:n,localAssetService:i}=ee(),{sessionPlayer:o}=t,a=s||"runner",c=this.options.timeout;Z.onWaitToTestComplete(this.id),o.playbackManager.executionId=e.executionId,o.playbackManager.executionName=e.executionName;let l;if(this.options.skipLoadBalancer){let g=this.options.deviceUdid||((p=this.testRunConfig.mobile)==null?void 0:p.staticAllocation.deviceUdid),{protocol:b,hostname:T,port:v,path:y}=await xt.getTDCDeviceConnection(this.options.gridData,g);l=`${b}://${T}:${v}${y}`}else l=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;o.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(f=this.options.company)==null?void 0:f.companyId,device:this.device,nativeApp:e.nativeApp},o.playbackManager.appiumApi=new n(l,this.activeSession.sessionId,ET.DOMParser,((h=this.device)==null?void 0:h.domMode)==="enhanced"),this.startKeepAlive(o.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let g=await new Promise((T,v)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:T,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:e.remoteRunId}).catch(v)});return this.stopKeepAlive(),await i.drain(),g.stepsResults=null,g.resultId=this.testResultId,{...g,...e.seleniumPerfStats.getStats()}}catch(g){throw Gr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:g}),this.stopKeepAlive(),g}};try{return await super.runTestOnce(e,t),await ce(m(),c,Ae.TEST_REACHED_CUSTOM_TIMEOUT_MSG)}catch(g){throw Gr.error("failed to run test once",{err:g}),g}}getUserAgentString(){return"Testim/CI-Branch:test"}}});var Ya,xT=I(()=>{"use strict";U();Xn();Q();Ya=class{constructor(e){this.id=e;this.driver=new Nr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof pe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function CT(){let r=await Promise.any(pR.map(async e=>{try{return await ve(e)}catch{return null}}));return r==null?void 0:r.ip}var pR,Qa,Za=I(()=>{"use strict";Ve();pR=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];Qa=({timeout:r})=>({timeout:r,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var AT,ec,PT=I(()=>{"use strict";AT=R(require("ws"));U();Za();ec=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=Qa({timeout:e}),s=new AT.default(this._cdpUrl,t),n=nr(o=>{s.once("open",o)}),i=nr(o=>{s.once("error",o)}).catch(()=>{s.close(),s.removeAllListeners()});return s.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([n,i]).then(()=>s),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),s=this._cdpCallbacks.get(t.id);s&&(this._cdpCallbacks.delete(t.id),t.error?s.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?s.reject(new Error(t.result.exceptionDetails.exception.description)):s.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,s){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((c,l)=>{this._cdpCallbacks.set(i,{resolve:c,reject:l})}),a={method:e,params:t,id:i};return s&&Object.assign(a,{sessionId:s}),n.send(JSON.stringify(a)),o}}});var rc,Hp,tc,kT=I(()=>{"use strict";U();rc=R(require("chrome-launcher"));zo();PT();Un();Hp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new ec}async init(e){var h,g,b,T;let{browserOptions:t,testName:s,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}=e,m=qo({browserOptions:t,testName:s,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}),p=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(b=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:b["goog:chromeOptions"])==null?void 0:T.args)??[],...rc.Launcher.defaultFlags().filter(v=>v!=="--disable-extensions")];this.chrome=await rc.launch({chromeFlags:p,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await Rr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),bs(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},tc=class{constructor(e){this.id=e;this.sessionId=ne();this.driver=new Hp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var qp={};q(qp,{WorkerExtension:()=>gi});function dR(r){return r instanceof Error&&"type"in r&&typeof r.type=="string"}function OT(r){return dR(r)?r:new Error(r)}var rt,gi,sc=I(()=>{"use strict";$e();Q();ni();U();W();Ft();ae();xT();kT();pt();rt=A("worker-ext"),gi=class extends $t{initPlayer(){return this.options.useChromeLauncher?new tc(this.id):new Ya(this.id)}async _getBrowserOnce(e,t,s,n){var o;let{driver:i}=s;try{return await i.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:J.EXTENSION,useLocalChromeDriver:this.options.useLocalChromeDriver,customCapabilities:e.customCapabilities})}catch(a){throw rt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:go(),initializedFromCache:ho(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,s,n){return Z.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,s,n)}isUsingChromeLauncher(e){return!!this.options.useChromeLauncher}async updateTestStatusOnGrid(e,t,s){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:s}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:s,executionId:n,testId:i}=this;M("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Ae.TEST_START_TIMEOUT_MSG)}catch(p){if(!(p instanceof pe))throw p;return rt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:s}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,p)=>{try{let f=await d.url(m);return p.driverUrlFinished=!0,f}catch(f){throw rt.error("error from driver.url",{err:f,testResultId:s,executionId:n,testId:i,url:m,urlLength:m.length}),f}},c=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},l=async()=>{var g;if(M("WorkerExtension runExtTest"),(g=this.options.lightweightMode)!=null&&g.disableRemoteStep||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Z.onWaitToTestStart(this.id),Z.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(b){throw rt.warn("failed to run test via CDP",{err:b}),b}}let{driver:m}=t,p={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let v=function(w){e.onCompletedCleanup(),rt.warn("on browser closed error detected",{err:w,testResultId:s,executionId:n,testId:i}),m.unregisterToClosedBrowser(v),m.unregisterToKeepAliveFailed(y),w.type=Yr.BROWSER_CLOSED,T.abort(w)},y=function(w){m.unregisterToClosedBrowser(v),m.unregisterToKeepAliveFailed(y),rt.warn("on keep alive failed error detected",{err:w,testResultId:s,executionId:n,testId:i}),w.type=Yr.KEEP_ALIVE_FAILED,T.abort(w)};var f=v,h=y;let b=await e.getRunTestUrl();Z.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,b,p),c(p)]),this.options.testStartTimeout,Ae.TEST_START_TIMEOUT_MSG)}catch(w){if(!(w instanceof pe))throw w;rt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:s,executionId:n,testId:i,...p}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let T=new AbortController;m.registerToClosedBrowser(v),m.registerToKeepAliveFailed(y);try{let w=ce(e.onCompleted(),this.testRunTimeout,Ae.TEST_COMPLETE_TIMEOUT_MSG),S=await zc(w,T.signal);m.unregisterToClosedBrowser(v),m.unregisterToKeepAliveFailed(y);try{await this.updateTestStatusOnGrid(m,!!S.success,S.reason)}catch(B){rt.error("Could not update the grid about the test status",{err:B})}m.isAlive()||(rt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let x=m.maxKeepAliveGap();return x>=3e4&&(rt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=x),{...S,...e.seleniumPerfStats.getStats()}}catch(w){throw rt.warn("timeout wait until test completed",{err:w,testResultId:s,executionId:n,testId:i}),OT(w)}finally{m.unregisterToClosedBrowser(v),m.unregisterToKeepAliveFailed(y)}}catch(b){throw rt.warn("failed to start url",{err:b}),OT(b)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await l()}catch(d){throw rt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Kp={};q(Kp,{WorkerExtensionSingleBrowser:()=>zp});var mR,fR,zp,Jp=I(()=>{"use strict";$e();U();W();lp();Ft();sc();mR=A("base-worker"),fR=500,zp=class extends gi{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:e}=this.userData||{};await si(this.id,this.releaseSlotOnTestFinished,e,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(e,t,s,n){return Z.onGetSession(this.id,`worker ${this.id}`,e.runMode),this._getBrowserOnce(e,t,s,n)}async getTestPlayer(e,t){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(mR.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(e,t)),this.testPlayer}async runTest(e,t,s){let n=this.handleQuarantine(e);if(n)return n;M("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,e.testId,e.testResultId,s,e.retryKey);e.baseUrl=i.config.baseUrl;let o=await this.getTestPlayer(e,t);return e.markClearBrowser(),await this.runTestOnce(e,o)}async runTestCleanup(){var e;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(e=this.options.lightweightMode)!=null&&e.general&&await ie(fR)}}});var Xp,nc,_T=I(()=>{"use strict";Xn();le();$e();Ql();pt();Gu();Q();W();ae();Iy();na();Xp=A("worker-manager"),nc=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let s=this.executionQueue.getNext();if(!s){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(s.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(s,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},s){if(e)switch(e){case J.SELENIUM:return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;case J.APPIUM:return t?(await Promise.resolve().then(()=>(ST(),vT))).WorkerLocalTma:(await Promise.resolve().then(()=>(RT(),IT))).WorkerAppium;default:return Yn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Jp(),Kp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(sc(),qp))).WorkerExtension}else switch(s){case(Br.find(n=>n===s)&&Yn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Jp(),Kp))).WorkerExtensionSingleBrowser;case Br.find(n=>n===s):return(await Promise.resolve().then(()=>(sc(),qp))).WorkerExtension;case ri.find(n=>n===s):return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;default:throw new C(`browser ${s} is not supported`)}}async createWorker(e,...t){let s=t[0],n=await this.getWorkerType({mode:s.mode,localTmaUrl:s.localTmaUrl},e);try{return M("before new Worker",s.mode),new n(this.executionQueue,...t)}finally{M("after new Worker",s.mode)}}async runTests(e,t,s,n,i,o,a,c){if(e&&e.length===0)return;let l=!1,d=0,m=(p,f)=>new Promise(h=>{var z,re,ge,ze,P,D,$,Y;let g=i.project,b=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new sa(s,n,e,i,o,t),this.combinedTestResults={};let T=((z=i.company)==null?void 0:z.ucid)||"",v=(re=i.company)==null?void 0:re.companyId,y=(ge=i.company)==null?void 0:ge.name,w=i.source||"cli",S=i.user,x=(ze=i.company)==null?void 0:ze.planType,_=(P=i.company)==null?void 0:P.isStartUp,B=(D=i.projectData)==null?void 0:D.name,G=($=i.projectData)==null?void 0:$.type,E=i.lightweightMode,k=(Y=i.gridData)==null?void 0:Y.type,L=(Le,Ot,Ee,Sc,Si,Ec)=>(d++,Eg({executionId:s,projectId:g,testId:Ot,resultId:Ee,ucid:T,companyId:v,companyName:y,projectName:B,companyPlan:x,source:w,user:S,lightweightMode:E,isStartUp:_,projectType:G,appSource:Ec,gridType:k}),t.testStartAndReport(Le,s,Ee,Sc,Si)),j=async(Le,Ot,Ee,Sc,Si,Ec)=>{var Kd,Jd,Xd;d--;let st={...(E==null?void 0:E.onlyTestIdsNoSuite)&&{show:!0},...Ee.seleniumStats&&{seleniumStats:Ee.seleniumStats},...Ee.gridIssues&&{gridIssues:Ee.gridIssues},...Ee.keepAliveIssue&&{keepAliveIssue:Ee.keepAliveIssue},...i.host&&{gridHost:i.host}};if(Ee.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(Ee.seleniumPerfMarks),delete Ee.seleniumPerfMarks),i.grid||i.gridId?(st.gridName=i.grid||((Kd=i.gridData)==null?void 0:Kd.name),st.gridType=(Jd=i.gridData)==null?void 0:Jd.type,st.gridProvider=(Xd=i.gridData)==null?void 0:Xd.provider):i.localTmaUrl?(st.gridName="local-tma-from-options",st.gridType="local-tma"):i.useLocalChromeDriver?(st.gridName="local-chrome-driver-from-options",st.gridType="local-chrome"):i.useChromeLauncher?(st.gridName="chrome-launcher-from-options",st.gridType="local-chrome"):i.browserstack?st.gridName="browserstack-from-options":i.saucelabs&&(st.gridName="saucelabs-from-options"),await t.testEndAndReport(Le,Ee,s,Sc,Si,st).catch(Jw=>Xp.error("testEndAndReport threw an error",{err:Jw})),Si)return;this.combinedTestResults[Ee.resultId]=Ee,Ig({executionId:s,projectId:g,testId:Ot,resultId:Ee.resultId,result:Ee,ucid:T,companyId:v,companyName:y,projectName:B,companyPlan:x,source:w,user:S,lightweightMode:E,logger:Xp,isStartUp:_,projectType:G,appSource:Ec}),c&&!Ee.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===b||l&&d===0)&&h(this.combinedTestResults)},V=(Le,Ot)=>{this.combinedTestResults[Ot.resultId]=Ot,t.onTestIgnored(Le,Ot.resultId),d--,(Object.keys(this.combinedTestResults).length===b||l&&d===0)&&h(this.combinedTestResults)},K=(Le,Ot)=>t.onGridSlot(Le,Ot);for(i.userData={loginData:{...Ar(),refreshToken:mo(),authData:Ar(),token:p,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:be()},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,s,L,j,K,V)});try{let p=await Nt(),f=await fo(),h=await m(p,f);if(this.workers.size>0&&this.workers.clear(),l)throw new rr;return h}catch(p){throw Xp.error("failed running parallel workers",{executionId:s,err:p}),p}}generateUniqueIds(e){return Array.from({length:e},(t,s)=>`worker-${s+1}`)}}});var hi,LT,ic,Yp,oc,js,Qp=I(()=>{"use strict";hi=R(require("lodash"));U();W();le();ae();$e();ds();Yl();Ql();ye();LT=require("uuid");Cg();U();Ft();ph();Q();_T();ue();na();({CLI_MODE:ic}=zt),Yp=A("test-plan-runner"),oc=class oc{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return oc._id}async runTestAllPhases(e,t,s,n,i,o,a,c){let l={},d=new nc(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,T=await d.runTests(e,c,o,a,i,n,g,!0);Object.assign(l,T)},p=async()=>{let g=Di||i.parallel,b=!1;M("right before this.workerManager.runTests");let T=await d.runTests(t,c,o,a,i,n,g,b);M("right after this.workerManager.runTests"),Object.assign(l,T)},f=async()=>{let g=i.afterParallel||1,T=await d.runTests(s,c,o,a,i,n,g,!1);Object.assign(l,T)};Rg({executionId:o,projectId:i.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await p(),M("right after runTestPlanTests"),await f(),l}catch(g){if(Yp.error("error running test plan",{err:g}),g instanceof rr)return c.markAllQueuedTests(o,he.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var T,v,y,w;if((T=i.lightweightMode)!=null&&T.disablePixelValidation)return;if(i.mode===ic.SELENIUM)try{let[{getSessionPlayer:S},{makeSDK:x}]=await Promise.all([Promise.resolve().then(()=>(Se(),dr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:_}=S();await ce(_.closeBatch(o,x),1e4);return}catch{}let b;try{if(!((w=(y=(v=i.company)==null?void 0:v.activePlan)==null?void 0:y.premiumFeatures)!=null&&w.applitools)||(b=await rd(i.project),hi.default.isEmpty(b)||!o))return;let{runKey:S,url:x}=b,_=require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}});await ce(_.closeBatches({settings:{batchIds:[o],serverUrl:x,apiKey:S}}),1e4)}catch{}}}async runTestPlan(e,t,s,n,i,o,a,c){var y,w,S;let l=ne(),d=n.project;Gm(l),e.forEach(x=>Object.assign(x,{isBeforeTestPlan:!0})),s.forEach(x=>Object.assign(x,{isAfterTestPlan:!0}));let m=[...e,...t,...s],p=new Fo(m,n,o,a),f=hi.default.chain(m).map(x=>{var _;return((_=x.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(y=n.lightweightMode)!=null&&y.onlyTestIdsNoSuite?[]:m.map(x=>x.name),b=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:s}:p.executionStart(l,d,this.startTime,i,g);M("before testListInfoPromise");let T=await b;(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite||Z.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,l,c,h),M("before runTestAllPhases");let v=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,l,i||"All Tests",p);return M("before executionEnd"),await p.executionEnd(l),M("after executionEnd"),{results:v,executionId:l,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(On.colorString(On.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await Zp(e,t.testOptimization)}catch(s){return this.handleReportFailure(s,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await ed(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){Yp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function s(d){return hi.default.flattenDeep(Object.values(d)).reduce((m,p)=>m.concat(p.beforeTests,p.tests,p.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await oe(e.testPlanIds,async d=>{let m=await yi(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(p=>{a.testPlans.push(p);let f=p._id;a.testPlansData[f]=m.testPlansData[f]})}),await oe(e.testPlan,async d=>{let m=await yi(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(p=>{a.testPlans.push(p);let f=p._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await yi(o,e.testPlan,e.testPlanIds,t,e.intersections);let c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==ic.APPIUM&&await ap(e,s(l)),await oe(c,async d=>{var h;let m=d.testPlanId;n[m]={};let p={...e};p.baseUrl||=d.startUrl,p.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,p.gridId||=d.gridId,e.grid&&delete p.gridId,p.gridData=await pg(e,d);let f=p.overrideExecutionName||d.name;return await oe(l[m],async g=>{let b=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,p,f,m,t);Z.onTestPlanFinished(b.results,d.name,this.startTime,b.executionId,!1),n[m][b.executionId]=b.results;let T=Object.keys(n[m]).map(S=>({executionId:S,status:op(n[m][S])})),v=Object.keys(n[m]).map(S=>n[m][S]).reduce((S,x)=>Object.assign(S,x),{}),y=op(v);Object.assign(i,v);let w=y?T[0].executionId:T.find(S=>!S.status).executionId;return await td(o,m,{success:y,executions:T,executionId:w}),b})})}async runAnonymousTestPlan(e,t){var c;Yp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let s=await xy(e,t);if(M("after getSuite"),!((c=s==null?void 0:s.tests[0])!=null&&c.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in s&&s.branch||t;let n=s;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===ic.APPIUM&&(a=await mi({appId:e.appId,projectId:e.project})),await oe(s.tests,async l=>{if(a&&l.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=l[0];m.resultId=e.resultId,l=[m]}e.mode!==ic.APPIUM&&await ap(e,l),M("right before runTestPlan");let d=await this.runTestPlan([],l,[],e,i,null,t,o);return M("right after runTestPlan"),await Z.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=Pn(),s=[];await this.reportTestRunnerStarted(e.project,e),ln(e)?s=await this.runTestPlans(e,t):s=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=hi.default.flattenDeep(s);return M("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}};oc._id=(0,LT.v4)();js=oc});var Pe={};q(Pe,{addTestRetry:()=>ku,clearTestResult:()=>np,deleteCloudflareTunnel:()=>pd,fetchLambdatestConfig:()=>Lu,fixGridAppIDStructure:()=>Lp,forceUpdateCloudflareTunnelRoutes:()=>ud,getAllGrids:()=>Xl,getAppDetails:()=>mi,getApplitoolsIntegrationData:()=>rd,getBrowserStackSessionMetaData:()=>IR,getCloudflareTunnel:()=>ld,getCustomCapabilitiesByName:()=>md,getEditorUrl:()=>vR,getFileUrl:()=>id,getGridSlot:()=>Jl,getHybridGridProvider:()=>Kl,getLabFeaturesByProjectId:()=>Hu,getMobileDevicesFromGrid:()=>fi,getRealData:()=>Eu,getS3Artifact:()=>jn,getS3ArtifactText:()=>Su,getSuiteTestList:()=>cp,getTestPlan:()=>wR,getTestPlanTestList:()=>yi,getTestResults:()=>Ur,getUsageForCurrentBillingPeriod:()=>ad,initializeUserWithAuth:()=>cd,isTestResultCompleted:()=>sp,keepAliveCompanySlots:()=>wu,keepAliveGrid:()=>ql,loadSfdcCredential:()=>od,loadTest:()=>ei,releaseCompanySlot:()=>bu,releaseGridSlot:()=>zl,reportExecutionFinished:()=>Uo,reportExecutionStarted:()=>Pu,reportRunnerFinished:()=>ed,reportRunnerStarted:()=>Zp,requestCompanySlot:()=>yu,saveRemoteStep:()=>zu,saveTestPlanResult:()=>td,updateCompanySlot:()=>Tu,updateExecutionTests:()=>Au,updateRemoteRunFailure:()=>dd,updateTestDataArtifact:()=>Bo,updateTestResult:()=>ua,updateTestStatus:()=>_r,uploadAppToGrid:()=>_p,uploadRunDataArtifact:()=>ip,validateUserAccessKey:()=>Gl});async function $s(){let r=await Nt();if(!r)throw new Error("Failed to get token from server");return{[fl]:js.id,Authorization:`Bearer ${r}`}}async function Ce({url:r,body:e,headers:t={},timeout:s,retry:n}){let i=await $s(),o={...t,...i};return We({url:`${be()}${r||""}`,body:e,headers:o,timeout:s,retry:n})}async function bR(r,e,t,s={},n=void 0){let i=await $s(),o={...s,...i};return await nn(`${be()}${r||""}`,e,t,o,n)}async function bi(r,e){let t=await $s();return await Qc(`${be()}${r||""}`,e,t)}async function NT(r,e){let t=await $s();return await sn(`${be()}${r||""}`,e,t)}async function TR(r,e){let t=await $s();return await Yc(`${be()}${r||""}`,e||void 0,t)}async function xe(r,e,t,s){let n=await $s();return await ve(`${be()}${r||""}`,e||void 0,n,s,t)}function jn(r,e){return(0,te.default)(()=>xe(`/storage${r}`,null,{isBinary:!0},e),{retries:se,factor:1})}function id(r,e){return(0,te.default)(()=>xe(`/files/fileUrl?${r}`,null,{isBinary:!0},e),{retries:se,factor:1})}function Su(r){return(0,te.default)(()=>TR(`/storage${r}`))}async function Zp(r,e){return await Ce({url:"/test-runner",body:{projectId:r,testOptimization:e}})}async function ed(r){return await NT("/test-runner",{projectId:r})}async function wR(r,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,te.default)(()=>xe("/testPlan",{projectId:r,name:e.join(",")}),{retries:se,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function od({branch:r,projectId:e}){let t=await(0,te.default)(()=>xe(`/branch/branchData/${encodeURIComponent(r)}`,{projectId:e}),{retries:se,factor:1});return t==null?void 0:t.sfdcCredential}function ei({testId:r,branch:e,projectId:t,skipSharedSteps:s=!1,useBranchMap:n=!0}){return(0,te.default)(()=>xe(`/test/${r}`,{projectId:t,branch:e,skipSharedSteps:s,useBranchMap:n}),{retries:se,factor:1})}function td(r,e,t){return(0,te.default)(()=>Ce({url:"/testPlan/result",body:{projectId:r,testPlanId:e,result:t}}),{retries:se,factor:1})}function _r(r,e,t,s,n,i,o=se){return(0,te.default)(()=>bi("/result/run/test",{runId:e,testId:t,resultId:s,status:n,projectId:r,runnerVersion:gR,...i}),{retries:o,factor:1})}function Au(r,e,t,s,n,i,o,a){return(0,te.default)(()=>bi("/result/run/tests",{runId:r,runnerStatuses:e,status:t,reason:s,success:n,startTime:i,endTime:o,projectId:a}),{retries:se,factor:1})}async function Pu({executionId:r,projectId:e,labels:t,startTime:s,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(vo(),wg));return Ce({timeout:9e4,url:"/result/run",body:{runId:r,projectId:e,labels:t,startTime:s,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:c,isLocalRun:l}},retry:3})}function Uo(r,e,t,s,n={},i=void 0,o=void 0){let a=Date.now();return(0,te.default)(()=>bi("/result/run",{runId:e,projectId:t,endTime:a,status:r,success:s,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:se,factor:1})}async function yi(r,e,t,s,n){return(0,te.default)(()=>Ce({url:"/testPlan/list",body:{projectId:r,names:e,planIds:t,branch:s,intersections:n},timeout:12e4}),{retries:se,factor:1})}function cp({projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}){return(0,te.default)(()=>Ce({url:"/suite/v2/list",body:{projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}}),{retries:se,factor:1})}async function mi({appId:r,projectId:e}){try{let t=await(0,te.default)(()=>xe(`/mobile-app/app/${r}?projectId=${e}`),{retries:se,factor:1});return Vt.omit(t,"version")}catch(t){throw new Error(`Could not load app with the ID ${r}`,{cause:t})}}async function ad(r){try{return await(0,te.default)(()=>xe(`/plan/project/${r}/usage-current-billing-period`),{retries:se,factor:1})}catch(e){Wt.error("failed getting usage for current billing period",{projectId:r,error:e});return}}function sp(r,e,t){return(0,te.default)(()=>xe(`/result/${r}/isComplete`,{projectId:e,testRetryKey:t}),{retries:se,factor:1})}function Ur(r,e,t,s){return(0,te.default)(()=>xe(`/test/v2/${r}/result/${e}`,{projectId:t,branch:s}),{retries:se,factor:1})}function ql(r,e){return Ce({url:`/grid/keep-alive?reqId=${ne()}`,body:{projectId:r,slots:e},timeout:1e4})}function zl(r,e,t,s,n){return Ce({url:`/grid/release?reqId=${ne()}`,body:{companyId:r,projectId:e,slotId:t,gridId:s,browser:n}})}function Kl(r){return Ce({url:"/grid/hybrid/provider",body:r})}function Jl(r){return(0,te.default)(()=>xe("/grid/grid-slot",{...r,reqId:ne()}),{retries:se,factor:1})}async function cd({projectId:r,token:e,branchName:t,lightweightMode:s,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d}){var m,p;try{return await(0,te.default)(()=>We({url:`${be()}/executions/initialize`,body:{projectId:r,token:e,branchName:t||"master",lightweightMode:s,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d},timeout:6e4}),{retries:se,factor:1})}catch(f){if(Wt.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((p=f.code)!=null&&p.includes("ENOTFOUND"))throw new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",b=h.clientMessage.bgColor||"bgBlack";console.log(sd.default[b](sd.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Wt.error("Error parsing error message from server",f)}throw f}}async function vR(){if(nt)return{editorUrl:nt};try{return await(0,te.default)(()=>xe("/system-info/editor-url"),{retries:se,onFailedAttempt:r=>{if(r.attemptNumber>=se)throw r},factor:1})}catch(r){return Wt.error("cannot retrieve editor-url from server",{err:r}),{editorUrl:"https://app.testim.io"}}}function Xl(r){return(0,te.default)(()=>xe("/grid",{companyId:r}),{retries:se,factor:1})}function Eu(r,e,t){return(0,te.default)(()=>xe(`/real-data/${e}?${t}&projectId=${r}`),{retries:se,factor:1})}function ua(r,e,t,s,n){return(0,te.default)(()=>Ce({url:"/result/test",body:{projectId:r,resultId:e,testId:t,testResult:s,remoteRunId:n}}),{retries:se,factor:1})}function np(r,e,t,s){return(0,te.default)(()=>Ce({url:"/result/test/clear",body:{projectId:r,resultId:e,testId:t,testResult:s}}),{retries:se,factor:1})}function zu(r,e,t,s){return(0,te.default)(()=>Ce({url:"/remoteStep",body:{projectId:r,resultId:e,stepId:t,remoteStep:s}}),{retries:se,factor:1})}function SR(r){return r.startsWith("/")?r:`/${r}`}function ER(r,e,t){let s=SR(r);return t&&(s=`/${t}${s}`),e&&(s=`/${e}${s}`),s}async function MT(r,e,t,s,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${ne()}${o||""}`,c=`${e}/${t}/${a}`,l=ER(c,yR,r),d=Buffer.from(DT.gzip(s,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,te.default)(()=>bR(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:se,factor:1}),l}function ku({projectId:r,runId:e,testId:t,newResultId:s,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,te.default)(()=>Ce({url:"/result/test/retry",body:{projectId:r,newResultId:s,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:se,factor:1})}async function rd(r){try{return await xe(`/integration/applitools/v3/connected?projectId=${r}`)}catch(e){return Wt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function ld(r,e){try{return await bi("/tunnel",{companyId:r,routes:e})}catch(t){return Wt.warn("could'nt get tunnel.",{err:t}),{}}}async function ud(r,e){try{return await Ce({url:`/tunnel/${e}`,body:{companyId:r}})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}async function pd(r,e){try{return await NT(`/tunnel/${e}`,{companyId:r})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}function dd(r){return We({url:`${be()}/result/remoteRunFailure`,body:r})}async function fi({projectId:r,projectType:e,gridId:t,companyId:s,selectors:n}){let i=`${hR}/mobileDevices/${t}/${s}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,te.default)(()=>xe(i,{projectId:r}),{retries:se,factor:1})}catch(o){return Wt.warn("could'nt get devices from grid.",{err:o}),null}}async function _p({projectId:r,gridId:e,app:t,timeout:s}){return(0,te.default)(()=>Ce({url:`/mobile-app/app/upload-to-grid?projectId=${r}&gridId=${e}`,body:t,timeout:s}),{retries:se,factor:1})}async function Lp(r){return(0,te.default)(()=>Ce({url:"/mobile-app/app/fix-grid-app-id",body:r}),{retries:se,factor:1})}async function yu(r,e){return(0,te.default)(()=>Ce({url:"/slot-management/request-slot",body:{companyId:r,projectId:e}}),{retries:se,factor:1})}async function bu(r,e,t){return(0,te.default)(()=>Ce({url:"/slot-management/release-slot",body:{companyId:r,projectId:e,slotId:t}}),{retries:se,factor:1})}async function Tu(r,e,t){return(0,te.default)(()=>bi("/slot-management/update-slot",{slotId:t.slotId,companyId:r,projectId:e,slot:t}),{retries:se,factor:1})}function wu(r,e,t){return Ce({url:`/slot-management/keep-alive?reqId=${ne()}`,body:{slots:t,companyId:r,projectId:e},timeout:1e4})}async function IR(r,e){return await ve(`${Xs}/sessions/${r}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function Gl(r){try{return await xe("/v2/project/validateUserAccessKey",r),!0}catch(e){return Wt.error("error validating user access key",{error:e}),!1}}async function md(r,e){let[t]=await xe("/capabilities?",{projectId:r,name:e});return t}var sd,Vt,DT,te,nd,gR,Wt,se,hR,yR,Lu,Hu,ip,Bo,ye=I(()=>{"use strict";sd=R(require("chalk")),Vt=R(require("lodash")),DT=R(require("pako"));U();le();ae();Ve();pt();te=R(require("p-retry")),nd=R(require("object-hash"));Q();W();Qp();gR=it(),Wt=A("testim service api"),se=3,hR="/grid",yR="test-result-artifacts";Lu=async(r,e)=>(0,te.default)(()=>xe("/grid/lt/config",{companyId:r,...e&&{projectId:e}}),{retries:se,factor:1}),Hu=async r=>(0,te.default)(()=>xe(`/labFeature/v2/project/${r}`),{retries:se,factor:1});ip=Vt.memoize(async(r,e,t,s)=>{if(!Vt.isEmpty(s))return await MT(r,e,t,JSON.stringify(s),"test-run-data","application/json")},(r,e,t,s)=>`${(0,nd.default)(s)}:${e}:${t}`),Bo=Vt.memoize(async(r,e,t,s,n)=>!s||Vt.isEmpty(s)?void 0:await MT(r,e,t,JSON.stringify((()=>{let o=Vt.clone(s);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:pl.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(r,e,t,s)=>`${(0,nd.default)(s)}:${e}:${t}`)});function ac(){return it()}var fd=I(()=>{"use strict";U()});function CR(r){J.EXTENSION!==r&&process.nextTick(()=>{try{(Se(),Fe(dr)).getSessionPlayer()}catch{}})}function AR(r){var e,t;(t=(e=r.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&r.clientConfig.clientMessages.forEach(s=>{let n=s.color||"yellow",i=s.bgColor||"bgBlack";console.log(gd.default[i](gd.default[n](s.text)))})}function PR(r,e){let{serviceUrl:t}=r;Ys(t),lt(async()=>r,Qr.CACHE_FN_NAME,Qr.TTL,{serviceUrl:t})(),qr.setRegion(fh[Ss(e)])}async function Ti(r){var y;let{project:e,token:t,userAccessKey:s,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:c,grid:l}=r,d=!!(n!=null&&n.general),m=!!(i||o),p=d?xR:RR,f=ac(),h=ol(),g=await Vf(),b=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{b=await CT()}catch(w){FT.error("failed to get public ip",w)}let T=!0;M("before initializeUserWithAuth");let v=await lt(async()=>(CR(a),T=!1,await cd({projectId:e,token:t,branchName:r.branch,lightweightMode:n,localGrid:m,publicIp:b,gridId:c,grid:l,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",p,{project:e,token:t,branchName:r.branch,lightweightModeGeneral:d,localGrid:m,gridId:c,grid:l,publicIp:b})();return AR(v),PR(v.clientConfig,e),r.publicIps=[v.clientPublicIp],M("after initializeUserWithAuth"),b&&v.clientPublicIp&&v.clientPublicIp!==b&&(FT.error("public ip mismatch",{publicIpFromExternalService:b,publicIpFromServices:v.clientPublicIp}),r.publicIps.push(b)),ig(v.authData,{projectId:e,token:t,userAccessKey:s,publicIp:v.clientPublicIp,initializedFromCache:T}),Tg((y=v.clientConfig)==null?void 0:y.segmentKey),v}var gd,FT,RR,xR,UT=I(()=>{"use strict";gd=R(require("chalk"));$e();ye();Kt();pt();Za();ae();W();ue();fd();U();us();le();$o();Pr();FT=A("initializeUserWithAuth"),RR=1e3*60*5,xR=1e3*60*60*10});async function $T(r){var s;let e=Promise.resolve();r.useLocalChromeDriver&&(r.chromeBinaryLocation=r.downloadBrowser?await po():r.chromeBinaryLocation,e=yn({projectId:r.project,userId:r.user},{chromeBinaryLocation:r.chromeBinaryLocation},!!((s=r.lightweightMode)!=null&&s.general)),r.useLocalChromeDriver=!0),!r.playerRequirePath&&r.mode!==J.EXTENSION&&await xr(r.playerLocation,r.canary),r.mode!==J.SELENIUM&&r.mode!==J.APPIUM&&!r.ext&&await Dl(r.extensionLocation);let t;if(r.installCustomExtension){let n=!!(r.useLocalChromeDriver||r.useChromeLauncher);t=await Ll(r.installCustomExtension,n)}return await e,t}async function WT(r){var o;kR.info("prepare MockNetwork",{location:r});let e=await sl(r),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>BT*1e6)throw new Error(`${hd} exceeded ${BT}MB`);let s;try{s=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${hd} cannot be parsed.${cc.EOL}${a}`)}let n=new jT.default;if(!n.validate(Il,s)){let a=(o=n.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(cc.EOL);throw new Error(`${hd} is malformed.${cc.EOL}${a}`)}return s.entries}var cc,jT,BT,hd,kR,yd=I(()=>{"use strict";cc=R(require("node:os"));U();Sf();Tn();jT=R(require("ajv"));ae();Ul();W();UT();BT=1,hd="JSON file supplied to --mock-network-pattern",kR=A("prepare runner")});function zT(r){return r.start&&ms(null,"cli-start-command",{downloadBrowser:!!r.downloadBrowser}),!!(r.startV2||r.start||r.agent)}async function KT(r){let e=!!r.start;if(Number.isNaN(r.agentPort))throw new C("Agent port is not number");let t=jo(r);return console.log("Start Testim CLI on Agent mode"),{project:r.project,token:r.token,agentMode:!0,agentPort:r.agentPort,agentBind:r.agentBind,openEditor:r.openEditor,startTestimBrowser:e,ext:r.ext,extensionPath:r.extensionPath,playerLocation:r.playerPath||t,canary:r.canary,playerPath:r.playerPath,playerRequirePath:r.playerRequirePath,downloadBrowser:!!r.downloadBrowser}}var JT=I(()=>{"use strict";Gn();Pr();Q()});var Ws,vd,XT=I(()=>{"use strict";Ws="SECRETS",vd={get secretsKey(){return Ws},get proxySecrets(){return new Proxy({},{get(r,e){return`${Ws}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[Ws]:this.proxySecrets})},containsSecrets(r){return typeof r=="string"?r.includes(Ws):JSON.stringify(r).includes(Ws)},extractSecretKeysFromCode(r){let e=new Set,s=(typeof r=="string"?r:JSON.stringify(r)).match(new RegExp(`${Ws}\\.\\w+`,"g"));return s==null||s.map(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:r,secretsRecord:e}){let s=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${s}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(n);if(l){let d=l[1];o[c]=e[d]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(n);if(l){let d=l[1];o[a]=e[d]??c}}else typeof c=="object"&&c!==null&&i(c)})};i(r)}}});var xd={};q(xd,{doLogin:()=>Rd,getProjectId:()=>MR,getToken:()=>FR});async function MR(){return ZT("projectId")}async function FR(){return ZT("token")}function QT(r,e){return Promise.race([r,ie(e).then(()=>{throw new pe("timeout")})])}async function UR(){let r=(await import("express")).default(),e=(async function(){return QT(new Promise(n=>{r.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)})();await new Promise((s,n)=>{let i=r.listen(42543,o=>{o&&n(o),s(i.address().port)})});try{let{getEditorUrl:s}=await Promise.resolve().then(()=>(ye(),Pe)),{editorUrl:n}=await s();_o(`${n}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${nt||wr}`)}return await e}async function Rd({overwriteExisting:r=!0,projects:e=null}={}){let t=Sd.homedir(),s=Ed.join(t,".testim");if(await Te(s)&&!r)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await QT(UR(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,c.succeed(),await YT(s,i);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=l.project.ci.token,i.projectId=l.project.id,await YT(s,i);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function YT(r,e){await Id.promises.writeFile(r,uc.stringify(e)),console.log(`Testim credentials saved in '${r}'`)}async function ZT(r){let e=Sd.homedir(),t=Ed.join(e,".testim"),s=await Te(t),n={};if(s)try{n=uc.parse((await Id.promises.readFile(t)).toString())}catch{}return n||={},n[r]}var Sd,Ed,uc,Id,pc=I(()=>{"use strict";Sd=R(require("os")),Ed=R(require("path")),uc=R(require("yaml"));U();Id=require("fs");Q();mu();le()});var lw={};q(lw,{process:()=>zR,program:()=>u});var Ad,iw,dc,ow,Pt,Oe,aw,BR,Me,jR,kd,$R,WR,tw,cw,wi,Pd,mc,Od,Cd,At,rw,sw,VR,GR,u,HR,qR,nw,zR,uw=I(()=>{"use strict";Ad=R(require("ms")),iw=R(require("chalk")),dc=R(require("node:fs")),ow=R(require("node:url")),Pt=R(require("lodash")),Oe=R(require("node:path"));U();Gn();JT();Kt();aw=require("commander");ae();Q();Hr();U();ue();XT();na();$o();le();Du();W();BR=r=>r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Me=(r,e)=>(e.push(r),e),jR=r=>(e,t)=>{if(t!==void 0)throw new C(`The ${r} flag can only be specified once.`);return e},kd=new aw.Command,$R=r=>r.split(","),WR=(r,e)=>!r||r.length===0?e:r,tw=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],cw=()=>{function r(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function s(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function p(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}kd.help(g=>g.split(`
|
|
406
|
-
`).filter(T=>!t(T)&&!e(T)&&!
|
|
407
|
-
`))},
|
|
408
|
-
WARNING: ${
|
|
409
|
-
`))},Pd=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:mc,argv:Od,exit:Cd,cwd:At}=global.process,rw={usw2:{ingestUrl:kc,token:Oc},euc1:{ingestUrl:um,token:pm}},sw={development:{usw2:{servicesUrl:"https://services.dev.testim.io"},euc1:{servicesUrl:"https://services.dev.eu.testim.io"}},staging:{usw2:{servicesUrl:"https://services.staging.testim.io"},euc1:{servicesUrl:"https://services.staging.eu.testim.io"}},production:{usw2:{servicesUrl:"https://services.testim.io"},euc1:{servicesUrl:"https://services.eu.testim.io"}}},VR=async r=>{let e=Ss(r),t=await os(Qr.CACHE_FN_NAME);if(t&&t.region===e){Ys(t.servicesUrl);return}let n=(sw[Js]||sw.production)[e]||{servicesUrl:"https://services.testim.io"};mc.SERVICES_HOST||Ys(n.servicesUrl),Wm(rw[e].ingestUrl||kc,rw[e].token||Oc)},GR=new Set(["trace","debug","info","warn","error","silent"]);gl(Od,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));kd.description("Testim.io CLI").option("-h --help","output usage information",cw).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-data [test-data]","test data file name to include in the test run").option("--test-config [test-config]","test config name to override for all tests in current execution",Me,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Me,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Me,[]).option("--test-id [test-id]","test ID to run",Me,[]).option("-l, --label [label]","labels to search test by",Me,[]).option("-n, --name [test-name]","test name to run",Me,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",$R).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Me,[]).option("--test-plan-id [test-plan-id]","test plan to run",Me,[]).option("--suite [suite-name]","suite to run",Me,[]).option("--suite-id [suite-id]","suite ID to run",Me,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",Me,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(mc.TESTIM_TEST_START_TIMEOUT)||120*1e3).option("--timeout [test-timeout]","Test run timeout in milliseconds",Number).option("--browser-timeout [open-browser-timeout]","Get browser from grid timeout in milliseconds",Number).option("--new-browser-wait-timeout [max-wait-to-browser]","Maximum get browser wait in minutes",Number).option("--get-browser-timeout [get-browser-timeout]","Timeout for a single attempt to get browser from the grid configured in the project's plan",Number).option("--get-browser-retries [get-browser-retries]","Number of attempts to get browser from the grid configured in the project's plan",Number).option("--get-session-timeout [get-session-timeout]",'Timeout for "/session" request to the selenium server',Number,(0,Ad.default)("90s")).option("--get-session-retries [get-session-retries]",'Retries for "/session" request to the selenium server',Number,3).option("--driver-request-timeout [driver-request-timeout]","Timeout for any WebDriver request to the grid server",Number,(0,Ad.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).option("--local-tma-url [local-tma-url]","use a local TMA instance for appium session").option("--use-local-chrome-driver [use-local-chrome-driver]","use a local ChromeDriver instance instead of a selenium grid").option("--chrome-binary-location [chrome-binary-location]","Chrome binary location").option("--use-chrome-launcher","use a local Chrome installation without selenium").option("-mnh --mock-network-har","use the HAR file configured in the Testim editor to mock network traffic").option("-mnp --mock-network-pattern [local file location path]","use a JSON rule file to mock network traffic (Rule file schema: https://help.testim.io/page/mocking-network-traffic)").option("-omf --override-mapping-file [local file location path]","pass map file location to override mock network (see schema: https://help.testim.io/page/mocking-network-traffic)").option("-dmn --disable-mock-network","Disable mock mode for the entire CLI run").option("--run-quarantined-tests","Run quarantine tests").option("--collect-code-coverage","collect code coverage for all js files under base url").option("--code-coverage-url-filter [url pattern]","collect code coverage for all js files matching url filter (url including asterisk)").option("--code-coverage-report-path [path]","where to save coverage report (default ./coverage)").option("--code-coverage-source-map-path [path]","path of source code").option("--code-coverage-reporter [reporter]",`set code coverage reporter (default html and text), options: ${Pd.join("/")}`,Me,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Me,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--sealights-lab-id [sealights-lab-id]","SeaLight Lab ID").option("--sealights-build-session-id [sealights-build-session-id]","SeaLight Session Build ID").option("--sealights-test-stage [sealights-test-stage]","SeaLight Test Stage Name").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Me,[]).option("--label-intersection-operand [operand]",'Run only tests that match either all the labels with the "AND" operand, or at least one of the labels with the "OR" operand',jR("--label-intersection-operand")).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",Me,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",Me,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").option("--custom-capabilities-name <name>","name of pre-created custom capabilities item").option("--custom-capabilities-file <path>","path to a JSON file with capabilities settings").parse(Od);u=kd.opts(),HR=()=>{u.grid||u.gridId||(u.host||(u.host="ondemand.saucelabs.com"),u.port||(u.port=80))},qR=()=>{u.grid||u.gridId||(u.host||(u.host="hub-cloud.browserstack.com"),u.port||(u.port=80))},nw=r=>{var s;if(!O.flags.secrets.isEnabled({projectId:u.project}))return;let t=dc.readFileSync(r);(s=vd)!=null&&s.containsSecrets(t.toString())&&vd.injectProxySecretsStoreToGlobal()},zR=async()=>{var v,y,w,S,x,_,B,G;u.inspect&&require("node:inspector").open(u.inspect);let r={},e={},t=[],s={},n;if(!Od.slice(2).length)throw cw(),new zr;if(u.version){let E="Testim CLI Version: ";mc.npm_package_version&&(console.log(E,mc.npm_package_version),Cd(0));let k=it();k&&(console.log(E,k),Cd(0)),console.log("Could not find version, please check the package.json manually"),Cd(0)}if(u.installLazyDeps)return{installLazyDepsMode:!0};u.disableFileCache&&Df(),u.clearFileCache&&as();let i=u.fileCacheLocation||u.usePrefechedData||u.createPrefechedData;if(i){let E=Oe.resolve(i);_f(E)}if(u.usePrefechedData&&Nf(),u.playerRequirePath){let E=Oe.resolve(u.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",E);let k=Oe.join(E,"tsconfig.node.json"),j=require("ts-node").register({project:k,ignore:[/node_modules/,new RegExp(`^${Pt.escapeRegExp(Oe.relative(At(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:j.config.options.paths,baseUrl:j.config.options.baseUrl}),(Se(),Fe(dr)).options.playerPath=E;let K=require("node:module"),z=K.prototype.require;K.prototype.require=function(ge){return ge==="rox-alias"?z.call(this,"rox-node"):ge==="canvas"?{}:z.apply(this,arguments)}}if(u.caFile&&(global.caFileContent=dc.readFileSync(u.caFile)),u.proxy&&(global.proxyUri=u.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),u.proxyForGrid&&!u.proxy)throw new C("missing --proxy option");if(zT(u))return KT(u);try{let E={};u.configFile?(nw(u.configFile),E=require(Oe.join(At(),u.configFile)).config):u.optionsFile&&(E=require(Oe.join(At(),u.optionsFile))),E&&typeof E.then=="function"&&(E=await E),Object.keys(E).forEach(k=>{let L=BR(k);u[L]=WR(u[L],E[k])})}catch(E){throw E.message=`Unable to read options file: ${E.message}`,E}if(u.tunneld)return{tunnel:!0,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:u.token,project:u.project};let o=((v=u.testConfig)==null?void 0:v.length)||((y=u.testConfigId)==null?void 0:y.length),a=((w=u.testPlan)==null?void 0:w.length)||((S=u.testPlanId)==null?void 0:S.length),c=((x=u.suite)==null?void 0:x.length)||((_=u.suiteId)==null?void 0:_.length);if(u.customCapabilitiesFile&&u.customCapabilitiesName)throw new C("You can either use --custom-capabilities-name or --custom-capabilities-file");if((u.customCapabilitiesFile||u.customCapabilitiesName)&&(u.browserstackOptions||u.sauceOptions||u.seleniumCapsFile||u.perfectoOptions))throw new C("Custom capabilities parameters can't be used together with --browserstack-options, --sauce-options, --selenium-caps-file or --perfecto-options parameters");if(u.customCapabilitiesFile)try{n=require(Oe.join(At(),u.customCapabilitiesFile)),Go(n)}catch(E){throw E instanceof C?E:new C(`Failed to parse custom capabilities file: ${E.message}`)}if(u.seleniumCapsFile){wi("--selenium-caps-file","--custom-capabilities-name or --custom-capabilities-file");try{s=require(Oe.join(At(),u.seleniumCapsFile))}catch(E){throw new C(`Failed to parse selenium caps file file error: ${E.message}`)}}if((B=u.reporters)!=null&&B.includes("junit")&&!u.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!u.tunnel&&u.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!u.tunnel&&u.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!u.tunnel&&[u.tunnelPort,u.tunnelHostHeader,u.tunnelRegion,u.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(u.chromeExtraPrefs)try{e=require(Oe.join(At(),u.chromeExtraPrefs))}catch(E){throw new C(`Failed to read/open chrome extra prefs file error: ${E.message}`)}if(u.chromeExtraArgs){let E=u.chromeExtraArgs.split(",");for(let k of E){let[L]=k.split("=");tw.includes(L)||u.useLocalChromeDriver||u.useChromeLauncher?(t.push(k),L==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.betterstackdata.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${L}), allowed values: ${JSON.stringify(tw)}`)}}if(u.paramsFile)try{u.paramsFile.endsWith("js")&&nw(u.paramsFile),r={...r,...require(Oe.join(At(),u.paramsFile))}}catch(E){throw new C(`Failed to read/open params file error: ${E.message}`)}if(u.params)try{r={...r,...JSON.parse(u.params)}}catch(E){throw new C(`Failed to parse params string error: ${E.message}`)}if(u.sauceUser&&!u.sauceKey||!u.sauceUser&&u.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(u.sauceUser&&u.sauceKey&&(HR(),u.saucelabs={},u.saucelabs.username=u.sauceUser,u.saucelabs.accessKey=u.sauceKey),u.sauceOptions){wi("--sauce-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(Oe.join(At(),u.sauceOptions)),k=E.platformName&&["ios","android"].includes(E.platformName.toLowerCase());if(E.browserName){let j=E.browserName.toLowerCase();j==="microsoftedge"?u.browser="edge":u.browser=j}u.browser==="edge"&&parseFloat(E.version)>=79&&(u.browser="edge-chromium");let L=parseFloat(E.version)<50&&!["dev","beta"].includes(E.version);if(!k&&u.browser==="chrome"&&L)throw new C("The minimum chrome supported version is 50.0");u.saucelabs={...u.saucelabs,...E}}catch(E){throw new C(`Failed to parse saucelabs options file error: ${E.message}`)}}if(u.browserstackUser&&!u.browserstackKey||!u.browserstackUser&&u.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(u.browserstackUser&&u.browserstackKey&&(qR(),u.browserstack={},u.browserstack["browserstack.user"]=u.browserstackUser,u.browserstack["browserstack.key"]=u.browserstackKey),u.browserstackOptions){wi("--browserstack-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(Oe.join(At(),u.browserstackOptions)),k=E.platform&&["mac","android"].includes(E.platform.toLowerCase());if(E.browserName&&(u.browser=E.browserName.toLowerCase()),u.browser==="edge"&&parseFloat(E.browser_version)>=79&&(u.browser="edge-chromium"),!k&&parseFloat(E.browser_version)<50&&u.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");u.browserstack={...u.browserstack,...E}}catch(E){throw new C(`Failed to parse browserstack options file error: ${E.message}`)}}if(u.perfecto={},u.perfectoToken&&(u.perfecto.securityToken=u.perfectoToken),u.perfectoOptions){wi("--perfecto-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(Oe.join(At(),u.perfectoOptions)),k={location:"US East",securityToken:u.perfectoToken};u.perfecto={...k,...E}}catch(E){throw new C(`Failed to parse perfecto options file error: ${E.message}`)}}if(u.testobjectSauce={},u.testobjectKey&&(u.testobjectSauce.testobjectApiKey=u.testobjectKey),u.testobjectOptions)try{let E=require(Oe.join(At(),u.testobjectOptions)),k={testobjectApiKey:u.testobjectKey};u.testobjectSauce={...k,...E}}catch(E){throw new C(`Failed to parse test object options file error: ${E.message}`)}let l={seaLights:{buildSessionId:u.sealightsBuildSessionId,labId:u.sealightsLabId,testStage:u.sealightsTestStage}};if(u.testOptimization=l,!u.project){let k=await(await Promise.resolve().then(()=>(pc(),xd))).getProjectId();if(k)u.project=k;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}VR(u.project),O.flags.forceTurboModeIfNeeded.isEnabled({projectId:u.project})&&(u.turboMode=!0),u.testConfig&&(u.testConfig=[u.testConfig].flat()),u.testConfigId&&(u.testConfigId=[u.testConfigId].flat()),u.retries=!u.retries||typeof u.retries=="boolean"?1:Number(u.retries)+1,u.browserTimeout=!u.browserTimeout||typeof u.browserTimeout=="boolean"?60*1e3:u.browserTimeout,u.newBrowserWaitTimeout=!u.newBrowserWaitTimeout||typeof u.newBrowserWaitTimeout=="boolean"?600*1e3:u.newBrowserWaitTimeout*60*1e3,u.getBrowserTimeout||(u.getBrowserTimeout=u.browserTimeout),u.getBrowserRetries||(u.getBrowserRetries=Math.round(u.newBrowserWaitTimeout/u.browserTimeout)),u.getSessionTimeout=Math.max(u.browserTimeout,u.getSessionTimeout),u.driverRequestTimeout=Math.max(u.browserTimeout,u.driverRequestTimeout);let m=!!u.timeout;if(u.timeout=!u.timeout||typeof u.timeout=="boolean"?600*1e3:u.timeout,u.beforeParallel=!u.beforeParallel||typeof u.beforeParallel=="boolean"?1:Number(u.beforeParallel),u.parallel=!u.parallel||typeof u.parallel=="boolean"?1:Number(u.parallel),u.afterParallel=!u.afterParallel||typeof u.afterParallel=="boolean"?1:Number(u.afterParallel),u.tunnelPort=!u.tunnelPort||typeof u.tunnelPort=="boolean"?"80":u.tunnelPort,u.port&&=Number(u.port),!u.token){let k=await(await Promise.resolve().then(()=>(pc(),xd))).getToken();if(k)u.token=k;else throw new C("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let p=E=>E<=0||!Number.isInteger(E);if(p(u.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(u.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(p(u.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(p(u.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(p(u.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(p(u.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(p(u.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(p(u.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(u.mode&&![J.EXTENSION,J.SELENIUM,J.APPIUM].includes(u.mode))throw new C(`runner mode <${u.mode}> is not supported`);if(u.browser&&![...Br,...ri].includes(u.browser))throw new C(`browser ${u.browser} is not supported`);if(u.mode!==J.SELENIUM&&u.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(u.appiumLogLevel||(u.appiumLogLevel="silent"),!GR.has(u.appiumLogLevel))throw new C(`runner appium-log-level <${u.appiumLogLevel}> is not supported`);if(u.testPlan&&u.testPlan.length===0&&u.testPlanId&&u.testPlanId.length===0){if(typeof u.host!="string"&&typeof u.grid!="string"&&typeof u.gridId!="string"&&!u.localTmaUrl&&!u.useLocalChromeDriver&&!u.useChromeLauncher&&!u.createPrefechedData&&!u.printGrids)throw new C("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(u.testId.length||u.label.length||u.name.length||o||u.browser||c||u.localTmaUrl||u.useLocalChromeDriver||u.useChromeLauncher)throw new C("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!a&&(u.beforeParallel!==1||u.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([u.host,u.grid,u.gridId].filter(Boolean).length>1)throw new C("please define exactly one of --grid or --grid-id or --host");if((G=u.host)!=null&&G.includes("/")&&(/^(f|ht)tps?:\/\//i.test(u.host)||(u.host=`http://${u.host}`),u.host=ow.parse(u.host).hostname),u.resultLabel.length){u.resultLabel=u.resultLabel.map(k=>k.trim()).filter(Boolean);let E=u.resultLabel.filter(k=>k.length>=250).filter(Boolean);if(u.branch==="auto-detect"&&u.resultLabel.includes("auto-detect-branch")&&Ir()&&u.resultLabel.unshift(Ir()),E.length)throw new C("A result label cannot exceed 250 characters")}let h=jo(u);if(!u.w3cCapabilities&&!u.oldCapabilities)throw new C("cannot set --w3c-capabilities and --old-capabilities options as false");if(u.protocol||=u.port===443?"https":"http",!["http","https"].includes(u.protocol))throw new C("invalid --protocol value, allow --protocol http or https");if(u.rerunFailedByRunId&&u.branch)throw new C("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(u.rerunFailedByRunId&&(c||u.name.length||u.testId.length||u.label.length||a))throw new C("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(u.setRetention&&!Pt.inRange(Pt.parseInt(u.setRetention),1,11))throw new C("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");u.setRetention&&=Number(u.setRetention);let g="is no longer supported, please use --override-mapping-file";if(u.mockNetworkHar)throw new C(`--mock-network-har ${g}`);if(u.mockNetworkPattern)throw new C(`--mock-network-pattern ${g}`);if(u.disableMockNetwork&&u.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!u.collectCodeCoverage&&u.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(u.collectCodeCoverage&&u.codeCoverageReporter&&Pt.difference(u.codeCoverageReporter,Pd).length){let E=Pt.difference(u.codeCoverageReporter,Pd);throw new C(`invalid --code-coverage-reporter parameters ${E.join("/")}`)}u.codeCoverageReporter=u.codeCoverageReporter.length===0?["html","text"]:u.codeCoverageReporter,u.codeCoverageInclude=u.codeCoverageInclude.length===0?["src/**"]:u.codeCoverageInclude;let b={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},T=Object.keys(b).filter(E=>!!u[E]);if([J.APPIUM,J.SELENIUM].includes(u.mode)&&T.length){let E=T.length>1?"are":"is";throw new C(`${T.map(k=>b[k]).join(" and ")} ${E} only applicable in extension mode`)}if((u.useChromeLauncher||u.useLocalChromeDriver)&&(u.browser="chrome"),u.tmsFieldFile)try{let E=dc.readFileSync(u.tmsFieldFile);u.tmsCustomFields=JSON.parse(E)}catch(E){throw new C(`failed to parse field file error: ${E.message}`)}if(u.applyIntersectionsToBeforeAndAfterSections&&!u.intersectWithLabel&&!u.intersectWithSuite&&!u.intersectWithSuiteId)throw new C("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(u.labelIntersectionOperand===!0)throw new C("The --label-intersection-operand flag requires a value. Please provide a value after the flag.");if(u.labelIntersectionOperand&&!Object.values(an).includes(u.labelIntersectionOperand))throw new C(`The --label-intersection-operand flag must be one of the following values: ${Object.values(an).join(", ")}`);if(u.labelIntersectionOperand&&Pt.isEmpty(u.intersectWithLabel))throw new C("The --label-intersection-operand flag must be used together with the --intersect-with-label flag.");if(u.highSpeed&&(wi("--high-speed","--turbo-mode"),u.turboMode=!0),u.skipLoadBalancer&&!u.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(u.deviceUdid&&(u.deviceName||u.osVersion))throw new C("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(u.setNoReset&&u.fullReset)throw new C("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(u.lightweightMode)try{let E={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},k=typeof u.lightweightMode=="string"?JSON.parse(u.lightweightMode):{};u.lightweightMode={...E,...k}}catch(E){throw new C(`failed to parse lightweightMode settings error: ${E.message}`)}else u.turboMode&&![J.APPIUM,J.SELENIUM].includes(u.mode)?u.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:u.turboMode&&[J.APPIUM,J.SELENIUM].includes(u.mode)&&console.warn(`
|
|
410
|
-
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof u.baseUrl=="boolean")throw new C("base url cannot be used as a flag, and must contain a string value");return{testId:[u.testId].flat(),name:[u.name].flat(),label:[u.label].flat(),suites:[u.suite].flat(),suiteIds:[u.suiteId].flat(),testPlan:[u.testPlan].flat(),testPlanIds:[u.testPlanId].flat(),reportFile:u.reportFile,urls:u.urls,reportFileClassname:u.overrideReportFileClassname,reporters:u.reporters,project:u.project,host:u.host,headless:u.headless,localTmaUrl:u.localTmaUrl,useLocalChromeDriver:u.useLocalChromeDriver,chromeBinaryLocation:u.chromeBinaryLocation,useChromeLauncher:u.useChromeLauncher,port:u.port,grid:u.grid,gridId:u.gridId,disableNativeEvents:u.disableNativeEvents,saucelabs:u.saucelabs,browserstack:u.browserstack,baseUrl:u.baseUrl,branch:(u.branch==="auto-detect"?Ir():u.branch)||"master",autoDetect:u.branch==="auto-detect",token:u.token,userAccessKey:u.userAccessKey,userParamsData:r,mode:u.mode,browser:u.browser,beforeParallel:u.beforeParallel,parallel:u.parallel,afterParallel:u.afterParallel,canary:u.canary,rerunFailedByRunId:u.rerunFailedByRunId,disableGridCheck:u.disableGridCheck,disableTimeoutRetry:u.disableTimeoutRetry,resultLabels:u.resultLabel,path:u.path,protocol:u.protocol,perfecto:u.perfecto,experitestToken:u.experitestToken,testobjectSauce:u.testobjectSauce,testOptimization:u.testOptimization,gridUsername:u.gridUsername,gridPassword:u.gridPassword,overrideExecutionName:u.overrideExecutionName,tmsSuppressReporting:!!u.suppressTmsReporting||!!u.tmsSuppressReporting,tmsRunId:u.tmsRunId,tmsCustomFields:u.tmsCustomFields,proxyForGrid:u.proxyForGrid,retentionDays:u.setRetention,passZeroTests:!!u.passZeroTests,runQuarantinedTests:!!u.runQuarantinedTests,deviceName:u.deviceName,deviceUdid:u.deviceUdid,customTag:u.customTag,osVersion:u.osVersion,duration:u.duration,skipLoadBalancer:u.skipLoadBalancer,lockDevice:u.lockDevice,appId:u.appId,appiumLogLevel:u.appiumLogLevel,setNoReset:u.setNoReset,fullReset:u.fullReset,ext:u.ext,extensionPath:u.extensionPath,extensionLocation:[u.extensionPath].filter(Boolean),playerLocation:u.playerPath||h,playerPath:u.playerPath,playerRequirePath:u.playerRequirePath,tunnel:u.tunnel,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,externalLambdatestTunnelId:u.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:u.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:u.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:u.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:!!u.externalLambdatestDisableAutomationTunneling,externalLambdatestMitm:!!u.externalLambdatestMitm,beforeTest:u.beforeTest,afterTest:u.afterTest,beforeSuite:u.beforeSuite,afterSuite:u.afterSuite,timeout:u.timeout,timeoutWasGiven:m,browserTimeout:u.browserTimeout,newBrowserWaitTimeout:u.newBrowserWaitTimeout,getBrowserTimeout:u.getBrowserTimeout,getBrowserRetries:u.getBrowserRetries,getSessionTimeout:u.getSessionTimeout,getSessionRetries:u.getSessionRetries,driverRequestTimeout:u.driverRequestTimeout,driverRequestRetries:u.driverRequestRetries,testStartTimeout:u.testStartTimeout,testConfigNames:u.testConfig,testConfigIds:u.testConfigId,overrideMappingFile:u.overrideMappingFile,disableMockNetwork:u.disableMockNetwork,codeCoverageUrlFilter:u.codeCoverageUrlFilter,collectCodeCoverage:u.collectCodeCoverage,codeCoverageReportPath:u.codeCoverageReportPath,codeCoverageSourceMapPath:u.codeCoverageSourceMapPath,codeCoverageReporter:u.codeCoverageReporter,codeCoverageInclude:u.codeCoverageInclude,executionId:u.executionId,remoteRunId:u.remoteRunId,schedulerId:u.schedulerId,source:u.source,resultId:u.resultId,installCustomExtension:u.installCustomExtension,w3cCapabilities:u.w3cCapabilities,oldCapabilities:u.oldCapabilities,chromeBlockLocation:u.chromeBlockLocation,chromeUserDataDir:u.chromeUserDataDir,retries:u.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:u.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:s,shouldMonitorPerformance:u.monitorPerformance,user:u.user,lightweightMode:u.lightweightMode,createPrefechedData:u.createPrefechedData,saveRCALocally:u.saveRcaLocally,exitCodeIgnoreFailingTests:u.exitCodeIgnoreFailingTests,disableSockets:u.disableSockets,intersections:{labels:u.intersectWithLabel.length?[u.intersectWithLabel].flat():void 0,suiteNames:u.intersectWithSuite.length?[u.intersectWithSuite].flat():void 0,suiteIds:u.intersectWithSuiteId.length?[u.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:u.applyIntersectionsToBeforeAndAfterSections,labelIntersectionOperand:u.labelIntersectionOperand},testDataFileName:u.testData,downloadBrowser:u.downloadBrowser,slotService:"mongo",printGrids:u.printGrids,printFinalCaps:u.printFinalCaps,customCapabilities:n,customCapabilitiesName:u.customCapabilitiesName}}});var _d,KR,Vs,pw,dw,Ld,mw,fw=I(()=>{"use strict";U();Q();W();ws();_d=A("testimNgrok"),KR=".whitelisted-ngrok.testim.io",Vs="",dw=async(r,e={})=>{if(!e.ngrokToken)throw new C("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${ne()}-${r.projectData.projectId}${KR}`);let s={proto:"http",addr:r.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};r.tunnelHostHeader&&(s.host_header=r.tunnelHostHeader),r.tunnelRegion&&(s.region=r.tunnelRegion);let i=await(await Ne("ngrok")).connect(s);r.tunnelUseHttpAddress&&i.startsWith("https://")?(_d.info("replace https to http"),Vs=i.replace("https://","http://")):Vs=i,r.tunnelDiagnostics&&Ld(),r.baseUrl=Vs},Ld=async(r=!0)=>{try{let t=(await Ne("ngrok")).getApi(),{tunnels:s}=await t.listTunnels(),n=s.find(i=>i.public_url===Vs);console.log("ngrok stats",n),_d.info("ngrok stats",{tunnel:n})}catch(e){_d.error("error collecting ngrok stats",{err:e})}r&&(pw=setTimeout(()=>Ld(),1e4))},mw=async r=>{if(!Vs)return;clearTimeout(pw),r.tunnelDiagnostics&&await Ld(!1),await(await Ne("ngrok")).disconnect(Vs)}});var kt,Md,gw,Fd,hw,fc,XR,YR,Nd,QR,gc,Dd,ZR,hc,vi,ex,tx,yw,bw,Tw=I(()=>{"use strict";kt=R(require("node:os")),Md=R(require("node:path")),gw=R(require("portfinder")),Fd=R(require("node:fs")),hw=R(require("node:child_process"));U();ye();W();fc=A("testimCloudflare"),XR="https://github.com/cloudflare/cloudflared/releases/download/2025.11.1/",YR={win32ia32:{path:"cloudflared-windows-386.exe",sha256:"1e76c0d4e6ff2576db46ad1a7397415729fbaf886b22aa49327f66185a2e8fc8"},win32x64:{path:"cloudflared-windows-amd64.exe",sha256:"413f9b24dc6e61a455564651524f167b8ce29ac4ccd40703dea7af93cd37ed39"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",sha256:"155a288fef19dba08f0c7145c16a207baf137462d8a1289a78bf8564f9e51244",extract:!0},darwinarm64:{path:"cloudflared-darwin-arm64.tgz",sha256:"45cfbb59a720f60b873906aa6469f8c4058f26be6d351c3e2920bc9cb4714273",extract:!0},linuxia32:{path:"cloudflared-linux-386",sha256:"bec7a150d54d5c9e950ed41b434678f302698ad4638693ac9166ad186e4bb945"},linuxx64:{path:"cloudflared-linux-amd64",sha256:"991dffd8889ee9f0147b6b48933da9e4407e68ea8c6d984f55fa2d3db4bb431d"}},Nd=kt.tmpdir(),QR=kt.platform()==="win32"?"cloudflared.exe":"cloudflared",gc=Md.join(Nd,QR),Dd=6e4,ZR=500,hc=null,vi=null,ex=async(r,e)=>{let t=`http://localhost:${e}/metrics`,s=new Promise((o,a)=>{r.on("error",c=>{let l=`Cloudflare tunnel process error: ${c.message}`;fc.error(l,{error:c}),a(new Error(l))}),r.on("exit",c=>{if(c!==0){let l=`Cloudflare tunnel exited with code ${c}`;fc.error(l,{code:c}),a(new Error(l))}})}),n=async()=>{for(;;){try{let c=(await(await fetch(t)).text()).match(/cloudflared_tunnel_ha_connections\s+(\d+)/);if(c&&Number(c[1])>=1)return}catch{}await ie(ZR)}},i=ie(Dd).then(()=>{let o=`Cloudflare tunnel connection timeout after ${Dd} seconds`;throw fc.error(o,{timeout:Dd}),new Error(o)});await Promise.race([n(),s,i])},tx=async()=>{if(await Te(gc))return;let e=YR[kt.platform()+kt.arch()];if(!e){let s=`tunnel on ${kt.platform()+kt.arch()} platform is not supported.`;throw fc.error(s,{platform:kt.platform()+kt.arch()}),new Error(s)}let t=e.extract?Md.join(Nd,e.path):gc;await Ye(`${XR}/${e.path}`,t),await al(t,e.sha256),e.extract&&await nl(t,Nd),await Fd.promises.chmod(gc,"755")},yw=async r=>{let e=r.baseUrl||`http://localhost:${r.tunnelPort||80}`,t="tunnelRoutes"in r&&r.tunnelRoutes||[e],[s]=await Promise.all([ld(r.company.companyId,t),tx()]);hc=s._id;let n=await gw.getPortPromise({port:9e3});vi=hw.spawn(gc,["--metrics",`localhost:${n}`,"tunnel","--no-autoupdate","run","--protocol","http2","--token",s.token],{stdio:["ignore","pipe","pipe"]}),await ex(vi,n),await ud(r.company.companyId,hc),"tunnelRoutesOutput"in r&&r.tunnelRoutesOutput&&await Fd.promises.writeFile(r.tunnelRoutesOutput,JSON.stringify(s.routesMapping,null,2)),r.baseUrl=`${r.tunnelUseHttpAddress?"http":"https"}://${s.routesMapping[e]}`},bw=async r=>{let e=[];return hc&&e.push(pd(r.company.companyId,hc)),vi&&e.push(new Promise((t,s)=>{vi.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),vi.kill()})),await Promise.all(e)}});var jd={};q(jd,{connect:()=>yc,disconnect:()=>bc,serveTunneling:()=>sx});var ww,Bd,vw,ht,Ud,yc,bc,sx,$d=I(()=>{"use strict";fw();Un();Tw();ue();pt();ww=R(require("ora"));W();ae();Vo();Bd=A("tunnel"),vw=r=>{var e;return[N.TESTIM_LAMBDATEST,N.HYBRID].includes((e=r.gridData)==null?void 0:e.type)&&r.gridData.tunnel==="lambdatest"&&r.gridData.tunnelUser&&r.gridData.tunnelUser.length>0&&r.gridData.tunnelKey&&r.gridData.tunnelKey.length>0},ht=(r,e,t)=>{var s,n,i;return Bd.info(`${t} tunnel, status: ${r}`,{companyId:(s=e.company)==null?void 0:s.companyId,projectId:(n=e.projectData)==null?void 0:n.projectId,testId:e.testId,desiredTunnel:(i=e.gridData)==null?void 0:i.tunnel,actualTunnel:t})},yc=async r=>{var s;if(!r.tunnel)return;let e;Ud=O.flags.useNgrokTunnel.isEnabled({projectId:(s=r.projectData)==null?void 0:s.projectId});let t=null;try{if(e=(0,ww.default)("Starting tunnel...").start(),vw(r))t="lambdatest",ht("connecting",r,t),await Xt.connectTunnel(r),ht("connected",r,t);else if(Ud){t="ngrok",ht("connecting",r,t);let n=Ar();await dw(r,n),ht("connected",r,t)}else t="cloudflare",ht("connecting",r,t),await yw(r),ht("connected",r,t);e.succeed()}catch(n){let i="Failed to start tunnel. Please contact support@testim.io";throw n.isInvalidCredsForLT&&(i="Could not connect to LambdaTest. Check your credentials and then try again."),Bd.error("Failed to open tunnel",{err:n}),e==null||e.fail(i),new Error(n.isInvalidCredsForLT?`${i}
|
|
411
|
-
${
|
|
412
|
-
We'll use the maximum of ${y} for now. To use more, you can adjust your command or upgrade your plan.`),
|
|
413
|
-
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),
|
|
404
|
+
const downloadAndUploadFile = ${OI()};
|
|
405
|
+
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await xb(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var Da,Na,Pb=I(()=>{"use strict";Da=require("url");fe();Na=class extends H{async updateBaseUrl(e){let t=new Da.URL(e),r=new Da.URL(this.context.recordedBaseUrl),i=new Da.URL(this.context.baseUrl);return t.host===r.host&&r.host!==i.host&&(t.host=i.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var Ma,kb=I(()=>{"use strict";fe();U();Ma=class extends H{async performAction(){await ie(this.step.durationMS||0)}}});var Fa,Ob=I(()=>{"use strict";fe();Fa=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var ln,_b=I(()=>{"use strict";fe();ln=class extends H{async runApiInAut(e){var i;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let n=await this.driver.executeCodeAsync(r,t,e);return(n==null?void 0:n.value)||{}}catch(n){throw(i=n==null?void 0:n.message)!=null&&i.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):n}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,i={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},n=t.sendViaWebApp?await this.runApiInAut(i):await this.runApiInBg(i),o=n.result||{},a={method:t.method,status:o.status,url:t.url};return n.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ua,Lb=I(()=>{"use strict";fe();Ua=class extends H{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Db,bp,Tp,Nb=I(()=>{"use strict";Db=R(require("@applitools/spec-driver-webdriverio"));kn();Se();bp=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=Kd["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:Db.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,i){let{EyeSdkBuilder:n}=ee(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return n.rememberCreatedBatch(r,i),o}},Tp=new bp});var Mb,wp,un,Fb=I(()=>{"use strict";Mb=R(require("lodash"));fe();W();Nb();wp=A("pixel-validation-step-action"),un=class extends H{async performAction(){var d,m;let{shouldUseVisualGrid:e,applitoolsSdkConfig:t,applitoolsSdkLogger:r,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let n=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},o=((m=t.batch)==null?void 0:m.id)||i,a=await Tp.getManager(e,this.context.config.applitoolsConcurrency||5,o,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},l;try{let p=await a.openEyes({driver:this.driver.client,config:t,logger:r}),h={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Mb.isPlainObject(n.applitoolsStepSettings)&&(Object.assign(h,n.applitoolsStepSettings),wp.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:n.applitoolsStepSettings})),await p.check({settings:h}),l={isApplitoolsSdkResult:!0,success:!0,eyesResults:await p.close()},wp.info("Applitools SDK step executed successfully (selenium mode)",{projectId:this.context.projectId})}catch(p){wp.error("Applitools SDK step failed",{err:p,info:p.info}),l={isApplitoolsSdkResult:!0,success:!1,err:p}}return await Tp.handleApplitoolsSdkResult(this.context,l,this.step)}}});var Ds,vp=I(()=>{"use strict";As();Q();Ia();Ds=class extends dr{async executeCliCode(){var h,g,b;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((b=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:b.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:n="",id:o=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:d}=t,m={config:t.config,data:t.data},p=t.data.timeToPlayStep,f=await Cs(n,o,a,m,c,l,d,p);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ue?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var mr,Ub=I(()=>{"use strict";vp();mr=class extends Ds{isFailedResult(e){return e===!1}}});var Ba,Bb=I(()=>{"use strict";vp();Ba=class extends Ds{isFailedResult(e){return!e}}});var ja,jb=I(()=>{"use strict";As();fe();Q();ja=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:i,stepResultId:n,timeToPlayBeforeExec:o}=this.context;try{return{data:await xs(e,r,i,t,n,o),success:!0}}catch(a){return a instanceof _t?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ue?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var $r,$b=I(()=>{"use strict";fe();$r=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var we,Wb=I(()=>{"use strict";fe();we=class extends H{async performAction(){var r,i;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((n,o)=>this.context.playback.sfdcAddLog(n,o)));t.log.info(`BEGIN STEP '${(i=(r=this.step).getStepPreview)==null?void 0:i.call(r)}'`);try{let n=this.context.sfdcTestActions;if(n===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,n,this.context)}}catch(n){return{success:!1,reason:n.reason||n.message,exception:n,shouldRetry:!1}}finally{t.releaseObjects()}}}});var $a,Vb=I(()=>{"use strict";fe();$a=class extends H{async performAction(){var r,i;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((n,o)=>this.context.playback.sfdcAddLog(n,o)));t.log.info(`BEGIN STEP '${(i=(r=this.step).getStepPreview)==null?void 0:i.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(n){return{success:!1,reason:n.reason||n.message,exception:n,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Wa,Gb=I(()=>{"use strict";fe();Wa=class extends H{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function _I(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Va(s,e){_I(LI,e),e.registerLocateStepActionUtils(nn.getUtils(s))}var LI,Sp=I(()=>{"use strict";$y();Gy();Zy();eb();rb();nb();cb();lb();ub();pb();fb();gb();hb();Tb();Sb();Ab();Pb();kb();Ob();_b();Lb();Fb();Ub();Bb();jb();$b();Wb();Vb();Gb();LI={locate:nn,scroll:Ta,mouse:wa,submit:Aa,text:Sa,"special-key":Ra,"user-code":Yt,"validation-code-step":Yt,"wait-for-code-step":Yt,"action-code-step":Yt,"condition-step":Ls,"skip-code-step":Ls,"element-code-step":Ls,"evaluate-expression":va,"text-validation":an,"wait-for-text-validation":an,"select-option":Ca,"drop-file":Oa,"input-file":La,hover:Pa,navigation:Na,wheel:ka,sleep:Ma,refresh:Fa,"keyboard-shortcut-step":xa,"api-validation":ln,"api-action":ln,"api-code-step":Yt,"extract-text":Ua,"simple-ui-verification":un,"wait-for-simple-ui-verification":un,"cli-validation-download-file":$r,"cli-wait-for-download-file":$r,"network-validation-step":$r,"cli-validation-code-step":mr,"cli-wait-for-code-step":mr,"cli-action-code-step":mr,"cli-api-code-step":mr,"cli-condition-step":Ba,"node-package":ja,"email-code-step":Yt,"cli-email-code-step":mr,"sfdc-internal-test-step":Wa,"sfdc-recorded-step":$a,"sfdc-step-login":we,"sfdc-step-loginas":we,"sfdc-step-logout":we,"sfdc-step-sobjectcreate":we,"sfdc-step-sobjectdelete":we,"sfdc-step-findrecord":we,"sfdc-step-quickaction":we,"sfdc-step-sobjectedit":we,"sfdc-step-sobjectvalidate":we,"sfdc-step-launchapp":we,"sfdc-step-wait-for-page-load":we,"sfdc-step-closeconsoletabs":we,"sfdc-step-relatedlistaction":we,"sfdc-step-permission-validation":we,"sfdc-step-convert-lead-to-opportunity":we,"sfdc-step-quotelineeditor":we,"sfdc-document-validation":$r,"sfdc-step-flow-screen-completion":we,"sfdc-step-sobjectverifyoptions":we}});var Hb,DI,Ns,Ep=I(()=>{"use strict";Hb=["simple-ui-verification","wait-for-simple-ui-verification"],DI=[...Hb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Ns=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=n=>{let o=this.getTotalStepTimeLeftToPlay(e,n),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),i=DI.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,i),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return Hb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,i=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),i)}}});var zb={};q(zb,{SeleniumTestPlayer:()=>pn});var qb,NI,pn,Ip=I(()=>{"use strict";U();qb=require("@applitools/eyes-sdk-core");Ki();Q();W();pp();My();hp();ya();By();yp();Se();Sp();Ep();le();NI=A("SeleniumTestPlayer"),pn=class{constructor(e,t,r,i,n=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Ns(ba());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=i??new Dr;let d=new ha(this.driver);this.stepActionFactory=new l(d),Va(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new fa(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Uy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new _s(this.driver),FrameLocator:m,portSelector:ga,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:qb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(!!r),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=n,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,i){i!=null&&i.isTabOpener&&this.tabService.addNewPopup(this.id,i.id).catch(()=>null)}async onDone(){var r,i;let{commonConstants:e}=ee(),t=1e3*60*2;try{await ae((r=this.driver)==null?void 0:r.end(),t)}catch(n){n instanceof ue&&await((i=this.driver)==null?void 0:i.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){NI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let i=r.at(-1);await this.tabService.addNewTab(this.id,i,e,t),await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let i=await this.driver.getTabIds(),n=[new URL(st||Tr).hostname].concat(r);for(let o of i.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(n.some(c=>a.url.includes(c))){this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var xp={};q(xp,{WorkerSelenium:()=>Rp});function FI(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Ga,MI,Rp,Cp=I(()=>{"use strict";U();je();rn();W();Mt();Xo();oe();lp();Q();Ip();Se();wt();Ga=A("worker-selenium"),MI=1e9,Rp=class extends jt{initPlayer(e){return new pn(this.id,e.runParams,this.options.shouldMonitorPerformance,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,r,i){M("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,e.runMode);let{driver:n}=r;this.windowUtils=new Os(this.id,n),r.clearSessionTabs();let{browserValue:o}=this.testRunConfig,a=e.baseUrl;try{let c=this.options.useLocalChromeDriver;await n.init({projectData:this.options.projectData,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:J.SELENIUM,customCapabilities:e.customCapabilities}),M("in WorkerSelenium after driver.init"),await r.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(a,MI),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let l=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&o==="firefox",d=c.message&&c.message==="invalid argument";throw c instanceof Ot||l||d?new Ot(`Page '${a}' is not available`):(Ga.error("failed to navigate to page",{baseUrl:a,err:c,whitelistedPublicIp:fo(),initializedFromCache:go()}),c)}}async runTestOnce(e,t){var d;let{manifestVersion:r,localAssetService:i}=ee(),{driver:n,sessionPlayer:o}=t,a=r||"runner";Z.onWaitToTestComplete(this.id),FI(o),o.playbackManager.executionId=e.executionId,o.playbackManager.executionName=e.executionName,this.options.mode===J.SELENIUM&&o.setLightweightMode(this.options.lightweightMode),e.sfdcCredential&&o.setSfdcCredential(e.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(c=(await Yi(this.options))[this.testId]);let l=async()=>ae(new Promise((m,p)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:e.remoteRunId,preloadedTest:c}).catch(p)}),this.testRunTimeout,Ae.TEST_COMPLETE_TIMEOUT_MSG).catch(m=>{var p;throw m instanceof ue&&((p=o.stopPlayingOnTestTimeout)==null||p.call(o)),m}).then(async m=>{await i.drain(),m.stepsResults=null,m.resultId=this.testResultId,n.isAlive()||(Ga.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),m.gridIssues="could not validate grid is alive");let p=n.maxKeepAliveGap();p>=3e4&&(Ga.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),m.keepAliveIssue=p);let h={...m,...e.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await n.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});n.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(e,t),M("right after super.runTestOnce in workerSelenium");let m=await l();return M("right after runSeleniumTest"),m}catch(m){throw Ga.error("failed to run test once",{err:m}),m}}}});var Kb,He,UI,Ap,Rt,Ha=I(()=>{"use strict";Kb=R(require("ora"));mp();le();We();ye();W();oe();Se();pe();He=A("mobile-grid-service"),UI="https://tdc.tricentis-cloud.com",Ap=class{constructor(){this.gridsAppIdGetter={[N.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[N.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[N.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[N.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return e.type===N.TESTIM_TDC?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===N.TESTIM_TDC?`${r||Oc}/${um}/devices`:""}getHeaders(e){return{...e.type===N.TESTIM_TDC&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...e.type===N.TESTIM_TDC&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),i=this.getHeaders(e),n=this.buildRequestBody(e,t);try{await $e({url:r,headers:i,body:n})}catch(o){throw He.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getTDCDeviceConnection(e,t){let i=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let n=await ve(i,void 0,this.getHeaders(e));return this.extractTDCDeviceConnection(n,e.accessToken)}catch(n){throw He.error("error while getting automation config for device",{error:n,deviceId:t}),n}}extractTDCDeviceConnection(e,t){let r=Object.keys(e)[0],i=e[r].driver_url,n=new URL(i);return{hostname:n.hostname,port:Number(n.port),protocol:n.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return e.type===N.TESTIM_TDC&&(r=await this.getTDCDeviceConnection(e,t)),r}getGridConnection(e){var r;if(e.type===N.TESTIM_TDC){let i=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:i}}if(e.type===N.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if([N.BROWSERSTACK,N.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:i,companyId:n,gridId:o}){var a,c,l;if(t===N.TESTIM_TDC){let d=await mn({projectId:r,projectType:i,companyId:n,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}return t===N.BROWSERSTACK?((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName):t===N.SAUCELABS?e.testobject_device_name:e.device}async updateDeviceOnRemoteTestResult(e,t,r,i,n=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:p="",type:f=""}={}}=i,h=t.capabilities,g=h.platformName,b;if(f===N.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:v}=ee();b=v(t.capabilities,n)}else b=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,d,m,p,n);let T=await this.buildRemoteResultLink(i.gridData,t.sessionId,h);return await Or(l,o,a,c,"RUNNING",{device:b,...T&&{remoteResultLink:T}}),He.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:b,remoteResultLink:T,gridType:f}),b}getOsVersion(e,t){var i;let r=e.platformVersion;return!r&&t===N.BROWSERSTACK?(i=e.mobile)==null?void 0:i.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,i,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),c=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:c}}try{let{AppiumApi:o}=ee(),a=new o(t,r.sessionId,null,n),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),{width:d,height:m}=await pa(c);return{scaleFactor:d/l.width,width:d,height:m}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:i==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,i,n,o,a,c,l,d){let[m,p]=await Promise.all([this.getScaleFactorAndSize(e,r,t,i,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:n,projectId:o,projectType:a,companyId:c,gridId:l})]),f=this.getOsVersion(e,n);return{name:p??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:i,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===N.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${zs}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===N.SAUCELABS?r.testobject_test_report_url:e.type===N.TESTIM_TVC?r.replayUrl:e.type===N.TESTIM_TDC?`${UI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let i=(await ve(`${e}/api/devices`)).find(n=>n.udid===t);if(!i)throw new Error(`device ${t} not found`);return{udid:i.udid,name:i.name,model:i.model,height:i.height,width:i.width,geo:"local",osVersion:i.osVersion,osType:i.deviceType.toLowerCase(),scaleFactor:i.scaleFactor??0,isVirtual:i.virtual??!1,minApiVersion:i.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:i,testId:n,testResultId:o}=r,{project:a,localTmaUrl:c}=t,l=await this.getTmaDeviceDetails(c,e);return await Or(a,i,n,o,"RUNNING",{device:l}),He.info("device details updated on testResult",{testResultId:o,executionId:i,testId:n,device:l}),l}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let i=e.type,n=t.mobileApp,o=this.gridsAppIdGetter[i]({testRunHandler:t,mobileApp:n,gridHost:e.host});return o?(O.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await kp({gridAppId:o,gridId:e.gridId,projectId:r,gridType:i,appId:n.appId,gridHost:e.host})),o):t.getAppPathByGridType(i,e.gridId,n)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let i=await dn({appId:e,projectId:t});return{appUrl:`${be()}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(lm*60))+1)*60*1e3,Math.max(cm,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:i,gridType:n}){let a={[N.BROWSERSTACK]:{name:"Browserstack"},[N.TESTIM_TVC]:{name:"Mobile Virtual Grid"}}[n].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let c=r||t.mobileApp,l=(0,Kb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Pp({projectId:e,gridId:i,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});return l.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw l.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:i,gridType:n,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:i,gridType:n});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let i="",n,{executionId:o,testResultId:a}=e,{appId:c="",project:l,authData:{token:d=""}={},gridData:m={}}=t,{gridId:p="",type:f=""}=m;if(!c&&e.isAppFromDevice)return i;if(c){He.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:d});i=T.appUrl,n=T.mobileApp,e.nativeApp=n}else He.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:o}),i=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:m,testRunHandler:e}),b=f===N.BROWSERSTACK||f===N.TESTIM_TVC;if(g){let T=t.projectData.type,v=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});v&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),i=g),!v&&b&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),i=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:p,gridType:f,mobileAppId:h})),!v&&!b&&He.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&b&&(i=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:p,gridType:f,mobileAppId:h})),i}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){let{accessToken:i,user:n,host:o,key:a,type:c,apiUrl:l}=t;if(c===N.BROWSERSTACK){let d=`${zs}/recent_apps`,m=await this.fetchWithUserAndPasswordAuth({url:d,user:n,key:a});return Array.isArray(m)?m.some(p=>p.app_url===e):!1}if(c===N.SAUCELABS){let d=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:d,user:n,key:a})).items.some(p=>p.id===e)}if(c===N.TESTIM_TDC){let d=`${l}/${_c}/apps`;return l||(d=`${Oc}/${_c}/apps`),(await this.fetchWithTokenAuth({url:d,accessToken:i,authType:"Bearer"})).apps.some(p=>p.app_id===e)}if(c===N.TESTIM_TVC){let d=`${pm}/versions/${e}/info`,m=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:d,accessToken:m,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(p){return p.status!==404&&He.error("error while verifying app exists on TVC",{error:p}),!1}}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let i={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await ve(e,void 0,i)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:i}){let n={Authorization:`${r} ${t}`,...i&&{"User-Agent":i}};return await ve(e,void 0,n)}},Rt=new Ap});function Xb({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!BI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function jI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==N.TESTIM_TDC)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function $I(s){let{testName:e,executionId:t,testResultId:r,customTag:i}=s,n=[{executionId:t},{testResultId:r}];return e&&n.push({testName:e}),i&&n.push({customTag:i}),n}function WI(s,e,t,r){let{fullReset:i,setNoReset:n,skipLoadBalancer:o}=e,c=s===N.TESTIM_TDC&&O.flags.enableBatchTDC.isEnabled(),l=O.flags.increaseTDCRequestTimeout.isEnabled();return{"tdc:options":{"tdc:capture.video":!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{"tdc:capture.network":!1},...o&&{"tdc:controlLock":!0},"tdc:retryNewSessionFailure":!1,"tdc:sessionTags":$I(t),"tdc:enableBatch":c,...!i&&{"appium:noReset":n},...l&&{"tdc:newCommandTimeout":600,"appium:newCommandTimeout":600},...r}}}function qa(s){return"id"in s?s.id:s.packageName}function VI(s){return{"tdc:app.id":s}}function GI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:i,androidActivityWait:n}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":i},l=i==null?void 0:i.startsWith("http");i&&!l&&(c=VI(i));let m=()=>o===void 0&&i?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{"appium:options":{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":qa(r)},...i&&c}};case"android":return{"appium:options":{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...n&&{"appium:appWaitActivity":`${n}, *`},...r&&{"appium:appPackage":qa(r),"appium:appActivity":r.activity??".*"},...i&&c}};default:throw Error(`unsupported mobile project ${s}`)}}function Ms({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,shouldRunInEnhancedMode:n}){let{"appium:options":o,...a}=e;switch(s){case"ios":return{"appium:options":{platformName:"iOS",autoAcceptAlerts:!0,automationName:n?"WaldoTestim":"XCUITest",fullReset:!0,...t&&{bundleId:qa(t)},...r&&{app:r},...o},...a};case"android":return{"appium:options":{platformName:"Android",autoGrantPermissions:!0,automationName:n?"WaldoTestim":"UiAutomator2",...i&&{appWaitActivity:`${i}, *`},...t&&{appPackage:qa(t),appActivity:t.activity??".*"},...r&&{app:r},...o},...a};default:throw Error(`unsupported mobile project ${s}`)}}function Yb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:i,options:n,gridInfo:o,shouldRunInEnhancedMode:a,customCapabilities:c}){let l=WI(o.type,n,i,c);return GI({projectType:s,sessionCaps:l,options:n,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function _p({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function Lp({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:i,dynamicAllocation:n}=e;return s||(i!=null&&i.deviceName?i.deviceName:n!=null&&n.deviceNameRegex?n.deviceNameRegex:t==="ios"&&r===N.BROWSERSTACK?"iPhone.*":".*")}function HI(s,e){let{androidToken:t,iosToken:r}=s,i=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(i&&!r)throw Error("missing ios token for testim virtual cloud");if(!i&&!t)throw Error("missing android token for testim virtual cloud");return i?r:t}function Qb(s,e,t){return s?Object.entries(s).reduce((r,[i,n])=>{if(e(i)){if(!t)return r[i]=n,r;let o=i.replace(t,"");r[o]=n}return r},{}):{}}function qI(s){return Qb(s,e=>e.startsWith("browserstack."),"browserstack.")}function zI(s){return Qb(s,e=>!e.startsWith("browserstack."))}function Zb(s){return!s||!eT(s)?"2.0.0":s}function eT(s){return s.split(".")[0]==="2"||s.includes("appium2")||["latest","stable"].includes(s)}function tT({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let i=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,n=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&n.test(s),c=e==="android"&&(i.test(s)||a),l=e==="ios"&&o.test(s),d=c||l;if(t){let m=eT(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Jb(s,e){let t={};return Object.entries(s).forEach(([r,i])=>{let n=r.startsWith(e)?r:`${e}${r}`;t[n]=i}),t}async function KI(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,options:n,gridInfo:o,sessionTags:a,testRunConfig:c,shouldRunInEnhancedMode:l,customCapabilities:d}=s,{osVersion:m,deviceName:p}=n,f=(c==null?void 0:c.mobile)||{},{type:h}=o,g=HI(o,e),b=await mn({gridId:o.gridId,projectType:e,projectId:n.project,companyId:n.company.companyId}),T=b==null?void 0:b.find(({udid:x})=>{var _;return((_=f.staticAllocation)==null?void 0:_.deviceUdid)===x}),v=(T==null?void 0:T.osVersion)??_p({osVersion:m,mobileConfig:f}),y=(T==null?void 0:T.name)??Lp({deviceName:p,mobileConfig:f,projectType:e,gridType:h}),w=ze(n.editorUrl,n.project,a.testId,a.testResultId,a.branch),S={"waldo:device":y,"waldo:os_version":v,"waldo:displayName":`${a.testName}-${a.executionId}-${a.testResultId}`,"waldo:externalUrl":w,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:token":g,...d};return S["waldo:options"]||(S["waldo:options"]={}),S["waldo:options"].token||(S["waldo:options"].token=g),Ms({projectType:e,sessionCaps:S,nativeAppMetadata:t,appPath:r,androidActivityWait:i,shouldRunInEnhancedMode:l})}function JI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:i,gridInfo:n,sessionTags:o,testRunConfig:a,customCapabilities:c}){let{osVersion:l,deviceName:d}=i,m=(a==null?void 0:a.mobile)||{},{type:p}=n,f=_p({osVersion:l,mobileConfig:m}),h=Lp({deviceName:d,mobileConfig:m,projectType:s,gridType:p}),g=(0,xt.omit)({...i.saucelabs},["automationName","platformName"]),b={...g["sauce:options"]};delete g["sauce:options"];let T={...c==null?void 0:c["sauce:options"]},v=(0,xt.omit)(c,"sauce:options"),y=b.appiumVersion||T.appiumVersion,w=g.platformVersion||v.platformVersion||f;if(tT({osVersion:w,projectType:s,appiumVersion:y})){let x={debug:!0,networkLogs:!0},_={user:n.user,key:n.key,name:o.testResultId,build:o.executionId,appiumVersion:Zb(y??"stable"),deviceName:h,tags:Object.values(o)},B={platformName:s==="android"?"Android":"iOS",browserName:"","appium:options":{platformVersion:f,deviceName:h,...g,...v},"sauce:options":{...x,..._,...(0,xt.omit)(b,"appiumVersion"),...(0,xt.omit)(T,"appiumVersion")}};return Ms({projectType:s,sessionCaps:B,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let S={"sauce:options":{"saucelabs.user":n.user,"saucelabs.key":n.key,tags:Object.values(o),name:o.testResultId,build:o.executionId},platformName:s==="android"?"Android":"iOS",browserName:"","appium:platformVersion":f,"appium:deviceName":h,"appium:device":h,...g,...b,...v,...T};return Ms({projectType:s,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function XI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,options:n,gridInfo:o,sessionTags:a,testRunConfig:c,customCapabilities:l}){let{osVersion:d,deviceName:m}=n,p=(c==null?void 0:c.mobile)||{},{type:f}=o,h=_p({osVersion:d,mobileConfig:p}),g=Lp({deviceName:m,mobileConfig:p,projectType:e,gridType:f}),b=qI(n.browserstack),T=(0,xt.omit)(zI(n.browserstack),["automationName","platformName","project","build","name"]),v={...l==null?void 0:l["bstack:options"]},y=(0,xt.omit)(l,"bstack:options"),w=b.appiumVersion||v.appiumVersion,S=T.platformVersion||y.platformVersion||h,x=O.flags.enableAppium2BrowserStack.isEnabled(),_={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`};if(x||tT({osVersion:S,projectType:e,isBrowserStack:!0,appiumVersion:w})){let G={..._,userName:o.user,accessKey:o.key,appiumVersion:x?"2.0.1":Zb(w),debug:!0,networkLogs:!0},E={"appium:options":{platformVersion:h,deviceName:g,...T,...y},"bstack:options":{...G,...(0,xt.omit)(b,"appiumVersion"),...(0,xt.omit)(v,"appiumVersion")}};return Ms({projectType:e,sessionCaps:E,nativeAppMetadata:t,appPath:r,androidActivityWait:i})}let B={..._,os_version:T.platformVersion||h,device:T.deviceName||g,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...T,...Jb(b,"browserstack."),...y,...Jb(v,"browserstack.")};return Ms({projectType:e,sessionCaps:B,nativeAppMetadata:t,appPath:r,androidActivityWait:i})}async function YI(s){if(N.TESTIM_TDC===s.gridInfo.type)return Yb(s);if(N.TESTIM_TVC===s.gridInfo.type)return await KI(s);if(N.SAUCELABS===s.gridInfo.type)return JI(s);if(N.BROWSERSTACK===s.gridInfo.type)return XI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function QI(s,e){var l,d;let{staticAllocation:t,dynamicAllocation:r,type:i}=e||{},{deviceName:n,osVersion:o,deviceUdid:a}=s,c={};return i==="dynamic"&&(!n&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(c.os_version=r.selector.osVersion)),i==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),n&&(c.manufacturer=n),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function rT(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:i,testRunConfig:n}=s,{selectedGrid:o}=(n==null?void 0:n.mobile)||{};if(n!=null&&n.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);Xb({nativeAppMetadata:t,appPath:i,gridInfo:e});let a=Rt.getGridConnection(e),c=await YI(s);if(e.type===N.TESTIM_TDC){let b=QI(r,n==null?void 0:n.mobile);if(!(0,xt.isEmpty)(b)){let T=Object.entries(b).map(([v,y])=>y.split(",").map(w=>w===".*"||w==="="?"":`${v}:${w}`).join(",")).join(" ").trim();c["tdc:selector"]=T}}let l=e.type===N.TESTIM_TVC?{alwaysMatch:c}:c,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,p=(0,Op.default)("2m"),f=(0,Op.default)("12m"),h=Sr(O.flags.appiumConnectionRetryCount.getValue(),m),g=Sr(O.flags.appiumConnectionRequestTimeout.getValue(),p);return d&&g<f&&(g=f),{...a,desiredCapabilities:c,connectionRetryTimeout:g,capabilities:l,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function sT(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:i,appPath:n,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=i;Xb({nativeAppMetadata:r,appPath:n,gridInfo:t}),jI({deviceUdid:l,gridInfo:t,testRunConfig:c});let d=l||((g=(h=c.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await Rt.getGridDirectConnection(t,d),f=Yb({projectType:e,nativeAppMetadata:r,appPath:n,androidActivityWait:o,options:i,sessionTags:a,testRunConfig:c,gridInfo:t});return d&&(f["appium:options"]||={},f["appium:options"]["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:i.appiumLogLevel}}function iT(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:i,customCapabilities:n}=s,o={...n,dontStopAppOnReset:!0,fullReset:!1},a=Ms({projectType:e,sessionCaps:o,nativeAppMetadata:t,appPath:r,androidActivityWait:i});return e==="ios"&&delete a["appium:options"].app,a}function nT(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Op,xt,BI,Dp=I(()=>{"use strict";Op=R(require("ms"));pe();oe();Ha();xt=require("lodash");U();ye();BI=[N.BROWSERSTACK,N.SAUCELABS,N.TESTIM_TDC,N.TESTIM_TVC]});var za,aT=I(()=>{"use strict";za=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Ka,cT=I(()=>{"use strict";U();Ka=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=ci;this.getLinksFromUnescapeHTML=li}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Np,Ja,lT=I(()=>{"use strict";W();Np=A("mobile-frame-locator-mock"),Ja=class{foundFrameCallback(){return Np.info("foundFrameCallback-mock invoked"),{}}locate(){return Np.info("locate-mock invoked"),{}}async findFrame(){return Np.info("findFrame-mock invoked"),{}}}});var ZI,pT,uT,Fs,Mp=I(()=>{"use strict";ZI=R(require("webdriverio")),pT=require("@applitools/eyes-sdk-core");aT();hp();W();cT();yp();Se();Sp();lT();Ep();uT=A("appium-test-player"),Fs=class{constructor(e,t,r,i=ZI,n=void 0,o=void 0){this.id=e;this.driver=i;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=ee(),m=new Ka(this.driver);this.stepActionFactory=new l(m),Va(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ns(ba()),this.sessionPlayer=new a(e,{tabService:new za,cookieUtils:void 0,FrameLocator:Ja,portSelector:ga,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:pT.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(!!r),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=n,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,i){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:i}=e,n={executionId:t,testResultId:r,sessionId:i==null?void 0:i.sessionId};try{i!=null&&i.sessionId&&(await(i==null?void 0:i.endSession()),uT.info("appium session deleted",{...n}))}catch(o){uT.error("error while deleting appium session",{...n,error:o})}finally{let{commonConstants:o}=ee();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function eR(s){return await ve(`${s}/api/status`)}async function dT(s,e){return await ve(`${s}/api/devices/${e}/status`)}async function mT(s){if((await eR(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var fT=I(()=>{"use strict";We()});var gT={};q(gT,{WorkerLocalTma:()=>jp});var Wr,Fp,Up,Bp,jp,hT=I(()=>{"use strict";We();Dp();rn();U();W();Mt();Mp();Se();fT();Ha();Wr=A("worker-appium"),Fp=class extends Error{},Up=class extends Error{},Bp=class extends Error{},jp=class extends jt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Fs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=ee(),{DOMParser:i}=await import("linkedom"),n=new r(this.sessionData.serverAddress,this.sessionData.sessionId,i,!1);return t.sessionPlayer.playbackManager.appiumApi=n,n}async getBrowserOnce(t,r,i,n){var S;if(Z.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:c}=this.options;await mT(o);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=i,p=c.type,f=this.options.appId;if(f){let{mobileApp:x}=await Rt.getMobileAppDataByAppId({appId:f,projectId:l,token:d});t.nativeApp=x}let h=p==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,b=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:v,version:y},w]=await Promise.all([this.getAppStateFromDevice(o,a,T),dT(o,a)]).catch(x=>{throw this.handleDeviceNotFoundError(x),x});if(Wr.info("device status and app state",{deviceStatus:w,appInstalled:v,version:y,executionId:this.executionId,testResultId:this.testResultId}),!v&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!v&&b&&(await this.installApp(o,a,b),Wr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let x={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(S=this.options.projectData)==null?void 0:S.name}-${this.options.project}`},_=iT({projectType:p,nativeAppMetadata:g,appPath:b,androidActivityWait:h,sessionTags:x,gridInfo:n,options:this.options,testRunConfig:this.testRunConfig,customCapabilities:t.customCapabilities}),B={capabilities:{udid:a,..._}};Wr.info("requesting new appium session from TMA",{tmaSessionSettings:B,executionId:this.executionId,testResultId:this.testResultId});let G=await this.requestNewAppiumSessionFromTma(o,B,g);this.sessionData=G;let E=await m.attach({sessionId:G.sessionId,capabilities:_});this.device=await Rt.updateTmaDeviceDetails(a,this.options,t),Wr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:E.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:E.capabilities})}catch(x){throw Wr.error("failed to start application",{err:x}),x}}async requestNewAppiumSessionFromTma(t,r,i){var n,o;try{let a=await $e({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:i.name,version:i.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(n=a.response)==null?void 0:n.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new Bp(c):a}}async getAppStateFromDevice(t,r,i){let n=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${n}`,c=(await ve(o)).find(l=>"id"in l?l.id===i:l.packageName===i);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,i){var n,o;try{let a=await Ht(i);await ti(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(n=a.response)==null?void 0:n.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new Up(l,{cause:a})}}handleDeviceNotFoundError(t){var i,n;let r=(n=(i=t.response)==null?void 0:i.body)==null?void 0:n.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Fp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:i,localAssetService:n}=ee(),{sessionPlayer:o}=r,a=i||"runner";Z.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device,nativeApp:t.nativeApp},await this.initAndGetAppiumAPI(r),n.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((m,p)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(p)});return await n.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw Wr.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw Wr.error("failed to run test once",{err:l}),l}}}});var bT={};q(bT,{WorkerAppium:()=>$p});var yT,Vr,$p,TT=I(()=>{"use strict";U();Dp();yT=require("linkedom");rn();W();Mt();Mp();Se();Ha();oe();hs();Vr=A("worker-appium"),$p=class extends jt{initPlayer(e){return new Fs(this.id,e.runParams,this.options.shouldMonitorPerformance,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,r,i){let n=this.options.projectData.type,o=(n==="android"||n==="ios")&&await e.isTestRecordedWithEnhancedMode();if(i.type!==N.TESTIM_TVC&&o)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Z.onGetSession(this.id,this.testName,e.runMode);let{driver:a}=r,c=await Rt.getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),l=n==="android"?e.androidActivityWait:null,d=e.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch},p={projectData:this.options.projectData,projectType:n,nativeAppMetadata:d,appPath:c,androidActivityWait:l,sessionTags:m,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:o,customCapabilities:e.customCapabilities},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Rt.lockDevice(i,this.options.deviceUdid),f=await sT(p)):f=await rT(p),Vr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:nT(f)}),f.headers={"User-Agent":this.getUserAgentString()};let h=this.getServerAddressFromGrid();this.activeSession=await a.remote(f),this.device=await Rt.updateDeviceOnRemoteTestResult(e,this.activeSession,h,this.options,o);let g=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),Vr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Vr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}startKeepAlive(e){let{errors:t}=ee(),r=async()=>{try{await e.getOrientation()}catch(i){Vr.error("failed to keep appium session alive",{err:i}),t!=null&&t.AppiumSessionTerminatedError&&i instanceof t.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(r,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(e){try{this.options.slotService==="redis"&&Dg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:e},this.id)}catch(t){Vr.error("failed to update slot data",{err:t})}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:r,type:i}=this.options.gridData;return i===N.TESTIM_TDC?`https://${e}:${t}/v0/${r}/wd/hub`:`https://${e}:${t}/wd/hub`}getDirectAddressConnection(){let{protocol:e,hostname:t,port:r,path:i}=this.activeSession.options;if(e&&t&&r&&i)return`${e}://${t}:${r}${i}`}async runTestOnce(e,t){var p,f,h;let{manifestVersion:r,AppiumApi:i,localAssetService:n}=ee(),{sessionPlayer:o}=t,a=r||"runner",c=this.options.timeout;Z.onWaitToTestComplete(this.id),o.playbackManager.executionId=e.executionId,o.playbackManager.executionName=e.executionName;let l;if(this.options.skipLoadBalancer){let g=this.options.deviceUdid||((p=this.testRunConfig.mobile)==null?void 0:p.staticAllocation.deviceUdid),{protocol:b,hostname:T,port:v,path:y}=await Rt.getTDCDeviceConnection(this.options.gridData,g);l=`${b}://${T}:${v}${y}`}else l=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;o.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(f=this.options.company)==null?void 0:f.companyId,device:this.device,nativeApp:e.nativeApp},o.playbackManager.appiumApi=new i(l,this.activeSession.sessionId,yT.DOMParser,((h=this.device)==null?void 0:h.domMode)==="enhanced"),this.startKeepAlive(o.playbackManager.appiumApi),n.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let g=await new Promise((T,v)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:T,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:e.remoteRunId}).catch(v)});return this.stopKeepAlive(),await n.drain(),g.stepsResults=null,g.resultId=this.testResultId,{...g,...e.seleniumPerfStats.getStats()}}catch(g){throw Vr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:g}),this.stopKeepAlive(),g}};try{return await super.runTestOnce(e,t),await ae(m(),c,Ae.TEST_REACHED_CUSTOM_TIMEOUT_MSG)}catch(g){throw Vr.error("failed to run test once",{err:g}),g}}getUserAgentString(){return"Testim/CI-Branch:test"}}});var Xa,wT=I(()=>{"use strict";U();Ki();Q();Xa=class{constructor(e){this.id=e;this.driver=new Dr}async onDone(){try{await ae(this.driver.end(),12e4)}catch(t){t instanceof ue&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function vT(){let s=await Promise.any(tR.map(async e=>{try{return await ve(e)}catch{return null}}));return s==null?void 0:s.ip}var tR,Ya,Qa=I(()=>{"use strict";We();tR=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];Ya=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var ST,Za,ET=I(()=>{"use strict";ST=R(require("ws"));U();Qa();Za=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=Ya({timeout:e}),r=new ST.default(this._cdpUrl,t),i=sr(o=>{r.once("open",o)}),n=sr(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([i,n]).then(()=>r),this._cdpWs}onCDPMessage(e){var i;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(i=t.result.exceptionDetails)!=null&&i.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let i=await this.initCDPWebsocket();this._lastWsId||=0;let n=this._lastWsId++,o=new Promise((c,l)=>{this._cdpCallbacks.set(n,{resolve:c,reject:l})}),a={method:e,params:t,id:n};return r&&Object.assign(a,{sessionId:r}),i.send(JSON.stringify(a)),o}}});var tc,Wp,ec,IT=I(()=>{"use strict";U();tc=R(require("chrome-launcher"));qo();ET();Ni();Wp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Za}async init(e){var h,g,b,T;let{browserOptions:t,testName:r,testRunConfig:i,gridInfo:n,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}=e,m=Ho({browserOptions:t,testName:r,testRunConfig:i,gridInfo:n,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}),p=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(b=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:b["goog:chromeOptions"])==null?void 0:T.args)??[],...tc.Launcher.defaultFlags().filter(v=>v!=="--disable-extensions")];this.chrome=await tc.launch({chromeFlags:p,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await Ir(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),ys(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},ec=class{constructor(e){this.id=e;this.sessionId=ce();this.driver=new Wp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Vp={};q(Vp,{WorkerExtension:()=>fn});function rR(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function RT(s){return rR(s)?s:new Error(s)}var tt,fn,rc=I(()=>{"use strict";je();Q();rn();U();W();Mt();oe();wT();IT();wt();tt=A("worker-ext"),fn=class extends jt{initPlayer(){return this.options.useChromeLauncher?new ec(this.id):new Xa(this.id)}async _getBrowserOnce(e,t,r,i){var o;let{driver:n}=r;try{return await n.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:t,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:J.EXTENSION,useLocalChromeDriver:this.options.useLocalChromeDriver,customCapabilities:e.customCapabilities})}catch(a){throw tt.error("failed to get browser",{err:a,gridInfo:i,whitelistedPublicIp:fo(),initializedFromCache:go(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,i){return Z.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,i)}isUsingChromeLauncher(e){return!!this.options.useChromeLauncher}async updateTestStatusOnGrid(e,t,r){var n;let i=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${i}`),"browserstack"in this.options&&((n=this.options.browserstack)!=null&&n["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:i,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:i,testId:n}=this;M("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ae(e.runTestUsingCDP(d.cdpTestRunner),m,Ae.TEST_START_TIMEOUT_MSG)}catch(p){if(!(p instanceof ue))throw p;return tt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,p)=>{try{let f=await d.url(m);return p.driverUrlFinished=!0,f}catch(f){throw tt.error("error from driver.url",{err:f,testResultId:r,executionId:i,testId:n,url:m,urlLength:m.length}),f}},c=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},l=async()=>{var g;if(M("WorkerExtension runExtTest"),(g=this.options.lightweightMode)!=null&&g.disableRemoteStep||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Z.onWaitToTestStart(this.id),Z.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(b){throw tt.warn("failed to run test via CDP",{err:b}),b}}let{driver:m}=t,p={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let v=function(w){e.onCompletedCleanup(),tt.warn("on browser closed error detected",{err:w,testResultId:r,executionId:i,testId:n}),m.unregisterToClosedBrowser(v),m.unregisterToKeepAliveFailed(y),w.type=Xr.BROWSER_CLOSED,T.abort(w)},y=function(w){m.unregisterToClosedBrowser(v),m.unregisterToKeepAliveFailed(y),tt.warn("on keep alive failed error detected",{err:w,testResultId:r,executionId:i,testId:n}),w.type=Xr.KEEP_ALIVE_FAILED,T.abort(w)};var f=v,h=y;let b=await e.getRunTestUrl();Z.onWaitToTestStart(this.id);try{await ae(Promise.all([a(t.driver,b,p),c(p)]),this.options.testStartTimeout,Ae.TEST_START_TIMEOUT_MSG)}catch(w){if(!(w instanceof ue))throw w;tt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:i,testId:n,...p}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let T=new AbortController;m.registerToClosedBrowser(v),m.registerToKeepAliveFailed(y);try{let w=ae(e.onCompleted(),this.testRunTimeout,Ae.TEST_COMPLETE_TIMEOUT_MSG),S=await qc(w,T.signal);m.unregisterToClosedBrowser(v),m.unregisterToKeepAliveFailed(y);try{await this.updateTestStatusOnGrid(m,!!S.success,S.reason)}catch(B){tt.error("Could not update the grid about the test status",{err:B})}m.isAlive()||(tt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let x=m.maxKeepAliveGap();return x>=3e4&&(tt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=x),{...S,...e.seleniumPerfStats.getStats()}}catch(w){throw tt.warn("timeout wait until test completed",{err:w,testResultId:r,executionId:i,testId:n}),RT(w)}finally{m.unregisterToClosedBrowser(v),m.unregisterToKeepAliveFailed(y)}}catch(b){throw tt.warn("failed to start url",{err:b}),RT(b)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await l()}catch(d){throw tt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Hp={};q(Hp,{WorkerExtensionSingleBrowser:()=>Gp});var sR,iR,Gp,qp=I(()=>{"use strict";je();U();W();op();Mt();rc();sR=A("base-worker"),iR=500,Gp=class extends fn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:e}=this.userData||{};await tn(this.id,this.releaseSlotOnTestFinished,e,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(e,t,r,i){return Z.onGetSession(this.id,`worker ${this.id}`,e.runMode),this._getBrowserOnce(e,t,r,i)}async getTestPlayer(e,t){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(sR.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(e,t)),this.testPlayer}async runTest(e,t,r){let i=this.handleQuarantine(e);if(i)return i;M("before runTest onTestStarted single browser");let n=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey);e.baseUrl=n.config.baseUrl;let o=await this.getTestPlayer(e,t);return e.markClearBrowser(),await this.runTestOnce(e,o)}async runTestCleanup(){var e;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(e=this.options.lightweightMode)!=null&&e.general&&await ie(iR)}}});var zp,sc,xT=I(()=>{"use strict";Ki();le();je();Jl();wt();$u();Q();W();oe();by();sa();zp=A("worker-manager"),sc=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let i=this.workerUniqueIds[t%this.parallelCount],n=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,n),n.id=t,n.uniqueId=i,n.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case J.SELENIUM:return(await Promise.resolve().then(()=>(Cp(),xp))).WorkerSelenium;case J.APPIUM:return t?(await Promise.resolve().then(()=>(hT(),gT))).WorkerLocalTma:(await Promise.resolve().then(()=>(TT(),bT))).WorkerAppium;default:return Ji.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(qp(),Hp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(rc(),Vp))).WorkerExtension}else switch(r){case(Ur.find(i=>i===r)&&Ji.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(qp(),Hp))).WorkerExtensionSingleBrowser;case Ur.find(i=>i===r):return(await Promise.resolve().then(()=>(rc(),Vp))).WorkerExtension;case en.find(i=>i===r):return(await Promise.resolve().then(()=>(Cp(),xp))).WorkerSelenium;default:throw new C(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],i=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return M("before new Worker",r.mode),new i(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,i,n,o,a,c){if(e&&e.length===0)return;let l=!1,d=0,m=(p,f)=>new Promise(h=>{var z,re,ge,qe,P,D,$,X;let g=n.project,b=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new ra(r,i,e,n,o,t),this.combinedTestResults={};let T=((z=n.company)==null?void 0:z.ucid)||"",v=(re=n.company)==null?void 0:re.companyId,y=(ge=n.company)==null?void 0:ge.name,w=n.source||"cli",S=n.user,x=(qe=n.company)==null?void 0:qe.planType,_=(P=n.company)==null?void 0:P.isStartUp,B=(D=n.projectData)==null?void 0:D.name,G=($=n.projectData)==null?void 0:$.type,E=n.lightweightMode,k=(X=n.gridData)==null?void 0:X.type,L=(Le,kt,Ee,vc,vn,Sc)=>(d++,yg({executionId:r,projectId:g,testId:kt,resultId:Ee,ucid:T,companyId:v,companyName:y,projectName:B,companyPlan:x,source:w,user:S,lightweightMode:E,isStartUp:_,projectType:G,appSource:Sc,gridType:k}),t.testStartAndReport(Le,r,Ee,vc,vn)),j=async(Le,kt,Ee,vc,vn,Sc)=>{var Wd,Vd,Gd;d--;let rt={...(E==null?void 0:E.onlyTestIdsNoSuite)&&{show:!0},...Ee.seleniumStats&&{seleniumStats:Ee.seleniumStats},...Ee.gridIssues&&{gridIssues:Ee.gridIssues},...Ee.keepAliveIssue&&{keepAliveIssue:Ee.keepAliveIssue},...n.host&&{gridHost:n.host}};if(Ee.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(Ee.seleniumPerfMarks),delete Ee.seleniumPerfMarks),n.grid||n.gridId?(rt.gridName=n.grid||((Wd=n.gridData)==null?void 0:Wd.name),rt.gridType=(Vd=n.gridData)==null?void 0:Vd.type,rt.gridProvider=(Gd=n.gridData)==null?void 0:Gd.provider):n.localTmaUrl?(rt.gridName="local-tma-from-options",rt.gridType="local-tma"):n.useLocalChromeDriver?(rt.gridName="local-chrome-driver-from-options",rt.gridType="local-chrome"):n.useChromeLauncher?(rt.gridName="chrome-launcher-from-options",rt.gridType="local-chrome"):n.browserstack?rt.gridName="browserstack-from-options":n.saucelabs&&(rt.gridName="saucelabs-from-options"),await t.testEndAndReport(Le,Ee,r,vc,vn,rt).catch(Bw=>zp.error("testEndAndReport threw an error",{err:Bw})),vn)return;this.combinedTestResults[Ee.resultId]=Ee,bg({executionId:r,projectId:g,testId:kt,resultId:Ee.resultId,result:Ee,ucid:T,companyId:v,companyName:y,projectName:B,companyPlan:x,source:w,user:S,lightweightMode:E,logger:zp,isStartUp:_,projectType:G,appSource:Sc}),c&&!Ee.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===b||l&&d===0)&&h(this.combinedTestResults)},V=(Le,kt)=>{this.combinedTestResults[kt.resultId]=kt,t.onTestIgnored(Le,kt.resultId),d--,(Object.keys(this.combinedTestResults).length===b||l&&d===0)&&h(this.combinedTestResults)},K=(Le,kt)=>t.onGridSlot(Le,kt);for(n.userData={loginData:{...Si(),refreshToken:po(),authData:Si(),token:p,userAccessKey:f},projectId:n.project,company:n.company,servicesUrl:be()},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(n,this.customExtensionLocalLocation,r,L,j,K,V)});try{let p=await Dt(),f=await mo(),h=await m(p,f);if(this.workers.size>0&&this.workers.clear(),l)throw new tr;return h}catch(p){throw zp.error("failed running parallel workers",{executionId:r,err:p}),p}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var gn,CT,ic,Kp,nc,Us,Jp=I(()=>{"use strict";gn=R(require("lodash"));U();W();le();oe();je();ps();Kl();Jl();ye();CT=require("uuid");vg();U();Mt();nh();Q();xT();pe();sa();({CLI_MODE:ic}=qt),Kp=A("test-plan-runner"),nc=class nc{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return nc._id}async runTestAllPhases(e,t,r,i,n,o,a,c){let l={},d=new sc(this.customExtensionLocalLocation),m=async()=>{let g=n.beforeParallel||1,T=await d.runTests(e,c,o,a,n,i,g,!0);Object.assign(l,T)},p=async()=>{let g=Ln||n.parallel,b=!1;M("right before this.workerManager.runTests");let T=await d.runTests(t,c,o,a,n,i,g,b);M("right after this.workerManager.runTests"),Object.assign(l,T)},f=async()=>{let g=n.afterParallel||1,T=await d.runTests(r,c,o,a,n,i,g,!1);Object.assign(l,T)};Tg({executionId:o,projectId:n.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await p(),M("right after runTestPlanTests"),await f(),l}catch(g){if(Kp.error("error running test plan",{err:g}),g instanceof tr)return c.markAllQueuedTests(o,he.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var T,v,y,w;if((T=n.lightweightMode)!=null&&T.disablePixelValidation)return;if(n.mode===ic.SELENIUM)try{let[{getSessionPlayer:S},{makeSDK:x}]=await Promise.all([Promise.resolve().then(()=>(Se(),ur)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:_}=S();await ae(_.closeBatch(o,x),1e4);return}catch{}let b;try{if(!((w=(y=(v=n.company)==null?void 0:v.activePlan)==null?void 0:y.premiumFeatures)!=null&&w.applitools)||(b=await Zp(n.project),gn.default.isEmpty(b)||!o))return;let{runKey:S,url:x}=b,_=require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}});await ae(_.closeBatches({settings:{batchIds:[o],serverUrl:x,apiKey:S}}),1e4)}catch{}}}async runTestPlan(e,t,r,i,n,o,a,c){var y,w,S;let l=ce(),d=i.project;Um(l),e.forEach(x=>Object.assign(x,{isBeforeTestPlan:!0})),r.forEach(x=>Object.assign(x,{isAfterTestPlan:!0}));let m=[...e,...t,...r],p=new Mo(m,i,o,a),f=gn.default.chain(m).map(x=>{var _;return((_=x.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(y=i.lightweightMode)!=null&&y.onlyTestIdsNoSuite?[]:m.map(x=>x.name),b=(w=i.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:p.executionStart(l,d,this.startTime,n,g);M("before testListInfoPromise");let T=await b;(S=i.lightweightMode)!=null&&S.onlyTestIdsNoSuite||Z.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,n,l,c,h),M("before runTestAllPhases");let v=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,i,l,n||"All Tests",p);return M("before executionEnd"),await p.executionEnd(l),M("after executionEnd"),{results:v,executionId:l,testPlanName:n,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(Ai.colorString(Ai.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await Xp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await Yp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){Kp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return gn.default.flattenDeep(Object.values(d)).reduce((m,p)=>m.concat(p.beforeTests,p.tests,p.afterTests),[])}let i={},n={},o=e.project,a={testPlans:[],testPlansData:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await ne(e.testPlanIds,async d=>{let m=await hn(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(p=>{a.testPlans.push(p);let f=p._id;a.testPlansData[f]=m.testPlansData[f]})}),await ne(e.testPlan,async d=>{let m=await hn(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(p=>{a.testPlans.push(p);let f=p._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await hn(o,e.testPlan,e.testPlanIds,t,e.intersections);let c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==ic.APPIUM&&await ip(e,r(l)),await ne(c,async d=>{var h;let m=d.testPlanId;i[m]={};let p={...e};p.baseUrl||=d.startUrl,p.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,p.gridId||=d.gridId,e.grid&&delete p.gridId,p.gridData=await ng(e,d);let f=p.overrideExecutionName||d.name;return await ne(l[m],async g=>{let b=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,p,f,m,t);Z.onTestPlanFinished(b.results,d.name,this.startTime,b.executionId,!1),i[m][b.executionId]=b.results;let T=Object.keys(i[m]).map(S=>({executionId:S,status:sp(i[m][S])})),v=Object.keys(i[m]).map(S=>i[m][S]).reduce((S,x)=>Object.assign(S,x),{}),y=sp(v);Object.assign(n,v);let w=y?T[0].executionId:T.find(S=>!S.status).executionId;return await Qp(o,m,{success:y,executions:T,executionId:w}),b})})}async runAnonymousTestPlan(e,t){var c;Kp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await wy(e,t);if(M("after getSuite"),!((c=r==null?void 0:r.tests[0])!=null&&c.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let i=r;if(e.rerunFailedByRunId&&!i.runName){if(!i.runExists)throw new C("Invalid run ID - no such run.");i.runName===""&&(i.runName=`rerun-${e.rerunFailedByRunId}`)}let n=e.overrideExecutionName||i.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===ic.APPIUM&&(a=await dn({appId:e.appId,projectId:e.project})),await ne(r.tests,async l=>{if(a&&l.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=l[0];m.resultId=e.resultId,l=[m]}e.mode!==ic.APPIUM&&await ip(e,l),M("right before runTestPlan");let d=await this.runTestPlan([],l,[],e,n,null,t,o);return M("right after runTestPlan"),await Z.onTestPlanFinished(d.results,n,this.startTime,d.executionId,o),d})}async run(e){let t=xi(),r=[];await this.reportTestRunnerStarted(e.project,e),ni(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let i=gn.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(i),M("right after onAllTestPlansFinished"),i.map(n=>n.results).reduce((n,o)=>Object.assign(n,o),{})}};nc._id=(0,CT.v4)();Us=nc});var Pe={};q(Pe,{addTestRetry:()=>Cu,clearTestResult:()=>tp,deleteCloudflareTunnel:()=>cd,fetchLambdatestConfig:()=>ku,fixGridAppIDStructure:()=>kp,forceUpdateCloudflareTunnelRoutes:()=>ad,getAllGrids:()=>zl,getAppDetails:()=>dn,getApplitoolsIntegrationData:()=>Zp,getBrowserStackSessionMetaData:()=>fR,getCloudflareTunnel:()=>od,getCustomCapabilitiesByName:()=>ud,getEditorUrl:()=>pR,getFileUrl:()=>rd,getGridSlot:()=>ql,getHybridGridProvider:()=>Hl,getLabFeaturesByProjectId:()=>Wu,getMobileDevicesFromGrid:()=>mn,getRealData:()=>wu,getS3Artifact:()=>Ui,getS3ArtifactText:()=>Tu,getSuiteTestList:()=>np,getTestPlan:()=>uR,getTestPlanTestList:()=>hn,getTestResults:()=>Fr,getUsageForCurrentBillingPeriod:()=>id,initializeUserWithAuth:()=>nd,isTestResultCompleted:()=>ep,keepAliveCompanySlots:()=>yu,keepAliveGrid:()=>Vl,loadSfdcCredential:()=>sd,loadTest:()=>Qi,releaseCompanySlot:()=>gu,releaseGridSlot:()=>Gl,reportExecutionFinished:()=>Fo,reportExecutionStarted:()=>xu,reportRunnerFinished:()=>Yp,reportRunnerStarted:()=>Xp,requestCompanySlot:()=>fu,saveRemoteStep:()=>Gu,saveTestPlanResult:()=>Qp,updateCompanySlot:()=>hu,updateExecutionTests:()=>Ru,updateRemoteRunFailure:()=>ld,updateTestDataArtifact:()=>Uo,updateTestResult:()=>la,updateTestStatus:()=>Or,uploadAppToGrid:()=>Pp,uploadRunDataArtifact:()=>rp,validateUserAccessKey:()=>$l});async function Bs(){let s=await Dt();if(!s)throw new Error("Failed to get token from server");return{[ml]:Us.id,Authorization:`Bearer ${s}`}}async function Ce({url:s,body:e,headers:t={},timeout:r,retry:i}){let n=await Bs(),o={...t,...n};return $e({url:`${be()}${s||""}`,body:e,headers:o,timeout:r,retry:i})}async function cR(s,e,t,r={},i=void 0){let n=await Bs(),o={...r,...n};return await ti(`${be()}${s||""}`,e,t,o,i)}async function yn(s,e){let t=await Bs();return await Yc(`${be()}${s||""}`,e,t)}async function PT(s,e){let t=await Bs();return await ei(`${be()}${s||""}`,e,t)}async function lR(s,e){let t=await Bs();return await Xc(`${be()}${s||""}`,e||void 0,t)}async function xe(s,e,t,r){let i=await Bs();return await ve(`${be()}${s||""}`,e||void 0,i,r,t)}function Ui(s,e){return(0,te.default)(()=>xe(`/storage${s}`,null,{isBinary:!0},e),{retries:se,factor:1})}function rd(s,e){return(0,te.default)(()=>xe(`/files/fileUrl?${s}`,null,{isBinary:!0},e),{retries:se,factor:1})}function Tu(s){return(0,te.default)(()=>lR(`/storage${s}`))}async function Xp(s,e){return await Ce({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function Yp(s){return await PT("/test-runner",{projectId:s})}async function uR(s,e){let t=i=>i===null?[]:typeof i=="string"&&JSON.parse(i)||i;return(await(0,te.default)(()=>xe("/testPlan",{projectId:s,name:e.join(",")}),{retries:se,factor:1})).map(({testConfigIds:i,beforeAllLabels:n,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(i),beforeAllLabels:t(n),testLabels:t(o),afterAllLabels:t(a)}))}async function sd({branch:s,projectId:e}){let t=await(0,te.default)(()=>xe(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:se,factor:1});return t==null?void 0:t.sfdcCredential}function Qi({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:i=!0}){return(0,te.default)(()=>xe(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:i}),{retries:se,factor:1})}function Qp(s,e,t){return(0,te.default)(()=>Ce({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:se,factor:1})}function Or(s,e,t,r,i,n,o=se){return(0,te.default)(()=>yn("/result/run/test",{runId:e,testId:t,resultId:r,status:i,projectId:s,runnerVersion:nR,...n}),{retries:o,factor:1})}function Ru(s,e,t,r,i,n,o,a){return(0,te.default)(()=>yn("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:i,startTime:n,endTime:o,projectId:a}),{retries:se,factor:1})}async function xu({executionId:s,projectId:e,labels:t,startTime:r,executions:i,config:n,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(wo(),fg));return Ce({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:i,status:"RUNNING",config:n,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:c,isLocalRun:l}},retry:3})}function Fo(s,e,t,r,i={},n=void 0,o=void 0){let a=Date.now();return(0,te.default)(()=>yn("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:i,remoteRunId:n,resultExtraData:o}),{retries:se,factor:1})}async function hn(s,e,t,r,i){return(0,te.default)(()=>Ce({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:i},timeout:12e4}),{retries:se,factor:1})}function np({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:i,suiteNames:n,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}){return(0,te.default)(()=>Ce({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:i,suiteNames:n,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}}),{retries:se,factor:1})}async function dn({appId:s,projectId:e}){try{let t=await(0,te.default)(()=>xe(`/mobile-app/app/${s}?projectId=${e}`),{retries:se,factor:1});return Wt.omit(t,"version")}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function id(s){try{return await(0,te.default)(()=>xe(`/plan/project/${s}/usage-current-billing-period`),{retries:se,factor:1})}catch(e){$t.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function ep(s,e,t){return(0,te.default)(()=>xe(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:se,factor:1})}function Fr(s,e,t,r){return(0,te.default)(()=>xe(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:se,factor:1})}function Vl(s,e){return Ce({url:`/grid/keep-alive?reqId=${ce()}`,body:{projectId:s,slots:e},timeout:1e4})}function Gl(s,e,t,r,i){return Ce({url:`/grid/release?reqId=${ce()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:i}})}function Hl(s){return Ce({url:"/grid/hybrid/provider",body:s})}function ql(s){return(0,te.default)(()=>xe("/grid/grid-slot",{...s,reqId:ce()}),{retries:se,factor:1})}async function nd({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:i,publicIp:n,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d}){var m,p;try{return await(0,te.default)(()=>$e({url:`${be()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:i,publicIp:n,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d},timeout:6e4}),{retries:se,factor:1})}catch(f){if($t.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((p=f.code)!=null&&p.includes("ENOTFOUND"))throw new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",b=h.clientMessage.bgColor||"bgBlack";console.log(ed.default[b](ed.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{$t.error("Error parsing error message from server",f)}throw f}}async function pR(){if(st)return{editorUrl:st};try{return await(0,te.default)(()=>xe("/system-info/editor-url"),{retries:se,onFailedAttempt:s=>{if(s.attemptNumber>=se)throw s},factor:1})}catch(s){return $t.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function zl(s){return(0,te.default)(()=>xe("/grid",{companyId:s}),{retries:se,factor:1})}function wu(s,e,t){return(0,te.default)(()=>xe(`/real-data/${e}?${t}&projectId=${s}`),{retries:se,factor:1})}function la(s,e,t,r,i){return(0,te.default)(()=>Ce({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:i}}),{retries:se,factor:1})}function tp(s,e,t,r){return(0,te.default)(()=>Ce({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:se,factor:1})}function Gu(s,e,t,r){return(0,te.default)(()=>Ce({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:se,factor:1})}function dR(s){return s.startsWith("/")?s:`/${s}`}function mR(s,e,t){let r=dR(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function kT(s,e,t,r,i,n="application/octet-stream"){let o=null;n==="application/json"&&(o=".json");let a=`${i}_${ce()}${o||""}`,c=`${e}/${t}/${a}`,l=mR(c,aR,s),d=Buffer.from(AT.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,te.default)(()=>cR(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:se,factor:1}),l}function Cu({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:i,previousTestResultId:n,testResult:o}){return(0,te.default)(()=>Ce({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:i,previousTestResultId:n,testId:t,runId:e,testResult:o}}),{retries:se,factor:1})}async function Zp(s){try{return await xe(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return $t.warn("could'nt get applitools integration data.",{err:e}),{}}}async function od(s,e){try{return await yn("/tunnel",{companyId:s,routes:e})}catch(t){return $t.warn("could'nt get tunnel.",{err:t}),{}}}async function ad(s,e){try{return await Ce({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){$t.warn("could'nt get tunnel.",{err:t});return}}async function cd(s,e){try{return await PT(`/tunnel/${e}`,{companyId:s})}catch(t){$t.warn("could'nt get tunnel.",{err:t});return}}function ld(s){return $e({url:`${be()}/result/remoteRunFailure`,body:s})}async function mn({projectId:s,projectType:e,gridId:t,companyId:r,selectors:i}){let n=`${oR}/mobileDevices/${t}/${r}?projectType=${e}`;n=i?`${n}&selectors=${encodeURIComponent(i)}`:n;try{return await(0,te.default)(()=>xe(n,{projectId:s}),{retries:se,factor:1})}catch(o){return $t.warn("could'nt get devices from grid.",{err:o}),null}}async function Pp({projectId:s,gridId:e,app:t,timeout:r}){return(0,te.default)(()=>Ce({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:se,factor:1})}async function kp(s){return(0,te.default)(()=>Ce({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:se,factor:1})}async function fu(s,e){return(0,te.default)(()=>Ce({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:se,factor:1})}async function gu(s,e,t){return(0,te.default)(()=>Ce({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:se,factor:1})}async function hu(s,e,t){return(0,te.default)(()=>yn("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:se,factor:1})}function yu(s,e,t){return Ce({url:`/slot-management/keep-alive?reqId=${ce()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function fR(s,e){return await ve(`${zs}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function $l(s){try{return await xe("/v2/project/validateUserAccessKey",s),!0}catch(e){return $t.error("error validating user access key",{error:e}),!1}}async function ud(s,e){let[t]=await xe("/capabilities?",{projectId:s,name:e});return t}var ed,Wt,AT,te,td,nR,$t,se,oR,aR,ku,Wu,rp,Uo,ye=I(()=>{"use strict";ed=R(require("chalk")),Wt=R(require("lodash")),AT=R(require("pako"));U();le();oe();We();wt();te=R(require("p-retry")),td=R(require("object-hash"));Q();W();Jp();nR=it(),$t=A("testim service api"),se=3,oR="/grid",aR="test-result-artifacts";ku=async(s,e)=>(0,te.default)(()=>xe("/grid/lt/config",{companyId:s,...e&&{projectId:e}}),{retries:se,factor:1}),Wu=async s=>(0,te.default)(()=>xe(`/labFeature/v2/project/${s}`),{retries:se,factor:1});rp=Wt.memoize(async(s,e,t,r)=>{if(!Wt.isEmpty(r))return await kT(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,td.default)(r)}:${e}:${t}`),Uo=Wt.memoize(async(s,e,t,r,i)=>!r||Wt.isEmpty(r)?void 0:await kT(s,e,t,JSON.stringify((()=>{let o=Wt.clone(r);if(i!=null&&i.hiddenParams){let a=i.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:ul.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,td.default)(r)}:${e}:${t}`)});function oc(){return it()}var pd=I(()=>{"use strict";U()});function yR(s){J.EXTENSION!==s&&process.nextTick(()=>{try{(Se(),Me(ur)).getSessionPlayer()}catch{}})}function bR(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let i=r.color||"yellow",n=r.bgColor||"bgBlack";console.log(dd.default[n](dd.default[i](r.text)))})}function TR(s,e){let{serviceUrl:t}=s;Ks(t),ct(async()=>s,Yr.CACHE_FN_NAME,Yr.TTL,{serviceUrl:t})(),Hr.setRegion(ch[ws(e)])}async function bn(s){var y;let{project:e,token:t,userAccessKey:r,lightweightMode:i,useLocalChromeDriver:n,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,d=!!(i!=null&&i.general),m=!!(n||o),p=d?hR:gR,f=oc(),h=nl(),g=await Ff(),b=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{b=await vT()}catch(w){OT.error("failed to get public ip",w)}let T=!0;M("before initializeUserWithAuth");let v=await ct(async()=>(yR(a),T=!1,await nd({projectId:e,token:t,branchName:s.branch,lightweightMode:i,localGrid:m,publicIp:b,gridId:c,grid:l,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",p,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:c,grid:l,publicIp:b})();return bR(v),TR(v.clientConfig,e),s.publicIps=[v.clientPublicIp],M("after initializeUserWithAuth"),b&&v.clientPublicIp&&v.clientPublicIp!==b&&(OT.error("public ip mismatch",{publicIpFromExternalService:b,publicIpFromServices:v.clientPublicIp}),s.publicIps.push(b)),Zf(v.authData,{projectId:e,token:t,userAccessKey:r,publicIp:v.clientPublicIp,initializedFromCache:T}),mg((y=v.clientConfig)==null?void 0:y.segmentKey),v}var dd,OT,gR,hR,_T=I(()=>{"use strict";dd=R(require("chalk"));je();ye();zt();wt();Qa();oe();W();pe();pd();U();ls();le();jo();Ar();OT=A("initializeUserWithAuth"),gR=1e3*60*5,hR=1e3*60*60*10});async function NT(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await uo():s.chromeBinaryLocation,e=mi({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},!!((r=s.lightweightMode)!=null&&r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==J.EXTENSION&&await Rr(s.playerLocation,s.canary),s.mode!==J.SELENIUM&&s.mode!==J.APPIUM&&!s.ext&&await Ll(s.extensionLocation);let t;if(s.installCustomExtension){let i=!!(s.useLocalChromeDriver||s.useChromeLauncher);t=await _l(s.installCustomExtension,i)}return await e,t}async function MT(s){var o;wR.info("prepare MockNetwork",{location:s});let e=await rl(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>LT*1e6)throw new Error(`${md} exceeded ${LT}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${md} cannot be parsed.${ac.EOL}${a}`)}let i=new DT.default;if(!i.validate(El,r)){let a=(o=i.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(ac.EOL);throw new Error(`${md} is malformed.${ac.EOL}${a}`)}return r.entries}var ac,DT,LT,md,wR,fd=I(()=>{"use strict";ac=R(require("node:os"));U();hf();gi();DT=R(require("ajv"));oe();Fl();W();_T();LT=1,md="JSON file supplied to --mock-network-pattern",wR=A("prepare runner")});function $T(s){return s.start&&ds(null,"cli-start-command",{downloadBrowser:!!s.downloadBrowser}),!!(s.startV2||s.start||s.agent)}async function WT(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=Bo(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:!!s.downloadBrowser}}var VT=I(()=>{"use strict";Wi();Ar();Q()});var js,bd,GT=I(()=>{"use strict";js="SECRETS",bd={get secretsKey(){return js},get proxySecrets(){return new Proxy({},{get(s,e){return`${js}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[js]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(js):JSON.stringify(s).includes(js)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${js}\\.\\w+`,"g"));return r==null||r.map(i=>{let n=i.split(".")[1];n&&e.add(n)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^${r}\\.(\\w+)$`),n=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(i);if(l){let d=l[1];o[c]=e[d]??a}}else typeof a=="object"&&a!==null&&n(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(i);if(l){let d=l[1];o[a]=e[d]??c}}else typeof c=="object"&&c!==null&&n(c)})};n(s)}}});var Ed={};q(Ed,{doLogin:()=>Sd,getProjectId:()=>xR,getToken:()=>CR});async function xR(){return zT("projectId")}async function CR(){return zT("token")}function qT(s,e){return Promise.race([s,ie(e).then(()=>{throw new ue("timeout")})])}async function AR(){let s=(await import("express")).default(),e=(async function(){return qT(new Promise(i=>{s.get("/loginInfo",(n,o)=>{i(JSON.parse(Buffer.from(n.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)})();await new Promise((r,i)=>{let n=s.listen(42543,o=>{o&&i(o),r(n.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ye(),Pe)),{editorUrl:i}=await r();Oo(`${i}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${st||Tr}`)}return await e}async function Sd({overwriteExisting:s=!0,projects:e=null}={}){let t=Td.homedir(),r=wd.join(t,".testim");if(await Te(r)&&!s)return;let n={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await qT(AR(),62e3).catch(()=>null)),e!=null&&e.token){n.token=e.token,n.projectId=e.projectId,c.succeed(),await HT(r,n);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});n.token=l.project.ci.token,n.projectId=l.project.id,await HT(r,n);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function HT(s,e){await vd.promises.writeFile(s,lc.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function zT(s){let e=Td.homedir(),t=wd.join(e,".testim"),r=await Te(t),i={};if(r)try{i=lc.parse((await vd.promises.readFile(t)).toString())}catch{}return i||={},i[s]}var Td,wd,lc,vd,uc=I(()=>{"use strict";Td=R(require("os")),wd=R(require("path")),lc=R(require("yaml"));U();vd=require("fs");Q();uu();le()});var sw={};q(sw,{process:()=>FR,program:()=>u});var Rd,ZT,pc,ew,At,Oe,tw,PR,Ne,kR,Cd,OR,_R,JT,rw,Tn,xd,dc,Ad,Id,Ct,XT,YT,LR,DR,u,NR,MR,QT,FR,iw=I(()=>{"use strict";Rd=R(require("ms")),ZT=R(require("chalk")),pc=R(require("node:fs")),ew=R(require("node:url")),At=R(require("lodash")),Oe=R(require("node:path"));U();Wi();VT();zt();tw=require("commander");oe();Q();Gr();U();pe();GT();sa();jo();le();Ou();W();PR=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ne=(s,e)=>(e.push(s),e),kR=s=>(e,t)=>{if(t!==void 0)throw new C(`The ${s} flag can only be specified once.`);return e},Cd=new tw.Command,OR=s=>s.split(","),_R=(s,e)=>!s||s.length===0?e:s,JT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],rw=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function i(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function n(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function p(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}Cd.help(g=>g.split(`
|
|
406
|
+
`).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!i(T)&&!a(T)&&!o(T)&&!n(T)&&!c(T)&&!l(T)&&!d(T)&&!m(T)&&!p(T)&&!f(T)&&!h(T)).join(`
|
|
407
|
+
`))},Tn=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(ZT.default.yellow(`
|
|
408
|
+
WARNING: ${s} is deprecated. ${t}
|
|
409
|
+
`))},xd=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:dc,argv:Ad,exit:Id,cwd:Ct}=global.process,XT={usw2:{ingestUrl:Pc,token:kc},euc1:{ingestUrl:im,token:nm}},YT={development:{usw2:{servicesUrl:"https://services.dev.testim.io"},euc1:{servicesUrl:"https://services.dev.eu.testim.io"}},staging:{usw2:{servicesUrl:"https://services.staging.testim.io"},euc1:{servicesUrl:"https://services.staging.eu.testim.io"}},production:{usw2:{servicesUrl:"https://services.testim.io"},euc1:{servicesUrl:"https://services.eu.testim.io"}}},LR=async s=>{let e=ws(s),t=await ns(Yr.CACHE_FN_NAME);if(t&&t.region===e){Ks(t.servicesUrl);return}let i=(YT[qs]||YT.production)[e]||{servicesUrl:"https://services.testim.io"};dc.SERVICES_HOST||Ks(i.servicesUrl),Mm(XT[e].ingestUrl||Pc,XT[e].token||kc)},DR=new Set(["trace","debug","info","warn","error","silent"]);fl(Ad,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Cd.description("Testim.io CLI").option("-h --help","output usage information",rw).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-data [test-data]","test data file name to include in the test run").option("--test-config [test-config]","test config name to override for all tests in current execution",Ne,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Ne,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Ne,[]).option("--test-id [test-id]","test ID to run",Ne,[]).option("-l, --label [label]","labels to search test by",Ne,[]).option("-n, --name [test-name]","test name to run",Ne,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",OR).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Ne,[]).option("--test-plan-id [test-plan-id]","test plan to run",Ne,[]).option("--suite [suite-name]","suite to run",Ne,[]).option("--suite-id [suite-id]","suite ID to run",Ne,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",Ne,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(dc.TESTIM_TEST_START_TIMEOUT)||120*1e3).option("--timeout [test-timeout]","Test run timeout in milliseconds",Number).option("--browser-timeout [open-browser-timeout]","Get browser from grid timeout in milliseconds",Number).option("--new-browser-wait-timeout [max-wait-to-browser]","Maximum get browser wait in minutes",Number).option("--get-browser-timeout [get-browser-timeout]","Timeout for a single attempt to get browser from the grid configured in the project's plan",Number).option("--get-browser-retries [get-browser-retries]","Number of attempts to get browser from the grid configured in the project's plan",Number).option("--get-session-timeout [get-session-timeout]",'Timeout for "/session" request to the selenium server',Number,(0,Rd.default)("90s")).option("--get-session-retries [get-session-retries]",'Retries for "/session" request to the selenium server',Number,3).option("--driver-request-timeout [driver-request-timeout]","Timeout for any WebDriver request to the grid server",Number,(0,Rd.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).option("--local-tma-url [local-tma-url]","use a local TMA instance for appium session").option("--use-local-chrome-driver [use-local-chrome-driver]","use a local ChromeDriver instance instead of a selenium grid").option("--chrome-binary-location [chrome-binary-location]","Chrome binary location").option("--use-chrome-launcher","use a local Chrome installation without selenium").option("-mnh --mock-network-har","use the HAR file configured in the Testim editor to mock network traffic").option("-mnp --mock-network-pattern [local file location path]","use a JSON rule file to mock network traffic (Rule file schema: https://help.testim.io/page/mocking-network-traffic)").option("-omf --override-mapping-file [local file location path]","pass map file location to override mock network (see schema: https://help.testim.io/page/mocking-network-traffic)").option("-dmn --disable-mock-network","Disable mock mode for the entire CLI run").option("--run-quarantined-tests","Run quarantine tests").option("--collect-code-coverage","collect code coverage for all js files under base url").option("--code-coverage-url-filter [url pattern]","collect code coverage for all js files matching url filter (url including asterisk)").option("--code-coverage-report-path [path]","where to save coverage report (default ./coverage)").option("--code-coverage-source-map-path [path]","path of source code").option("--code-coverage-reporter [reporter]",`set code coverage reporter (default html and text), options: ${xd.join("/")}`,Ne,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Ne,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--sealights-lab-id [sealights-lab-id]","SeaLight Lab ID").option("--sealights-build-session-id [sealights-build-session-id]","SeaLight Session Build ID").option("--sealights-test-stage [sealights-test-stage]","SeaLight Test Stage Name").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","DEPRECATED: use --custom-capabilities-name or --custom-capabilities-file instead. JSON file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Ne,[]).option("--label-intersection-operand [operand]",'Run only tests that match either all the labels with the "AND" operand, or at least one of the labels with the "OR" operand',kR("--label-intersection-operand")).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",Ne,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",Ne,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").option("--custom-capabilities-name <name>","name of pre-created custom capabilities item").option("--custom-capabilities-file <path>","path to a JSON file with capabilities settings").parse(Ad);u=Cd.opts(),NR=()=>{u.grid||u.gridId||(u.host||(u.host="ondemand.saucelabs.com"),u.port||(u.port=80))},MR=()=>{u.grid||u.gridId||(u.host||(u.host="hub-cloud.browserstack.com"),u.port||(u.port=80))},QT=s=>{var r;if(!O.flags.secrets.isEnabled({projectId:u.project}))return;let t=pc.readFileSync(s);(r=bd)!=null&&r.containsSecrets(t.toString())&&bd.injectProxySecretsStoreToGlobal()},FR=async()=>{var v,y,w,S,x,_,B,G;u.inspect&&require("node:inspector").open(u.inspect);let s={},e={},t=[],r={},i;if(!Ad.slice(2).length)throw rw(),new qr;if(u.version){let E="Testim CLI Version: ";dc.npm_package_version&&(console.log(E,dc.npm_package_version),Id(0));let k=it();k&&(console.log(E,k),Id(0)),console.log("Could not find version, please check the package.json manually"),Id(0)}if(u.installLazyDeps)return{installLazyDepsMode:!0};u.disableFileCache&&Af(),u.clearFileCache&&os();let n=u.fileCacheLocation||u.usePrefechedData||u.createPrefechedData;if(n){let E=Oe.resolve(n);xf(E)}if(u.usePrefechedData&&Pf(),u.playerRequirePath){let E=Oe.resolve(u.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",E);let k=Oe.join(E,"tsconfig.node.json"),j=require("ts-node").register({project:k,ignore:[/node_modules/,new RegExp(`^${At.escapeRegExp(Oe.relative(Ct(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:j.config.options.paths,baseUrl:j.config.options.baseUrl}),(Se(),Me(ur)).options.playerPath=E;let K=require("node:module"),z=K.prototype.require;K.prototype.require=function(ge){return ge==="rox-alias"?z.call(this,"rox-node"):ge==="canvas"?{}:z.apply(this,arguments)}}if(u.caFile&&(global.caFileContent=pc.readFileSync(u.caFile)),u.proxy&&(global.proxyUri=u.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),u.proxyForGrid&&!u.proxy)throw new C("missing --proxy option");if($T(u))return WT(u);try{let E={};u.configFile?(QT(u.configFile),E=require(Oe.join(Ct(),u.configFile)).config):u.optionsFile&&(E=require(Oe.join(Ct(),u.optionsFile))),E&&typeof E.then=="function"&&(E=await E),Object.keys(E).forEach(k=>{let L=PR(k);u[L]=_R(u[L],E[k])})}catch(E){throw E.message=`Unable to read options file: ${E.message}`,E}if(u.tunneld)return{tunnel:!0,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:u.token,project:u.project};let o=((v=u.testConfig)==null?void 0:v.length)||((y=u.testConfigId)==null?void 0:y.length),a=((w=u.testPlan)==null?void 0:w.length)||((S=u.testPlanId)==null?void 0:S.length),c=((x=u.suite)==null?void 0:x.length)||((_=u.suiteId)==null?void 0:_.length);if(u.customCapabilitiesFile&&u.customCapabilitiesName)throw new C("You can either use --custom-capabilities-name or --custom-capabilities-file");if((u.customCapabilitiesFile||u.customCapabilitiesName)&&(u.browserstackOptions||u.sauceOptions||u.seleniumCapsFile||u.perfectoOptions))throw new C("Custom capabilities parameters can't be used together with --browserstack-options, --sauce-options, --selenium-caps-file or --perfecto-options parameters");if(u.customCapabilitiesFile)try{i=require(Oe.join(Ct(),u.customCapabilitiesFile)),Vo(i)}catch(E){throw E instanceof C?E:new C(`Failed to parse custom capabilities file: ${E.message}`)}if(u.seleniumCapsFile){Tn("--selenium-caps-file","--custom-capabilities-name or --custom-capabilities-file");try{r=require(Oe.join(Ct(),u.seleniumCapsFile))}catch(E){throw new C(`Failed to parse selenium caps file file error: ${E.message}`)}}if((B=u.reporters)!=null&&B.includes("junit")&&!u.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!u.tunnel&&u.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!u.tunnel&&u.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!u.tunnel&&[u.tunnelPort,u.tunnelHostHeader,u.tunnelRegion,u.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(u.chromeExtraPrefs)try{e=require(Oe.join(Ct(),u.chromeExtraPrefs))}catch(E){throw new C(`Failed to read/open chrome extra prefs file error: ${E.message}`)}if(u.chromeExtraArgs){let E=u.chromeExtraArgs.split(",");for(let k of E){let[L]=k.split("=");JT.includes(L)||u.useLocalChromeDriver||u.useChromeLauncher?(t.push(k),L==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.betterstackdata.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${L}), allowed values: ${JSON.stringify(JT)}`)}}if(u.paramsFile)try{u.paramsFile.endsWith("js")&&QT(u.paramsFile),s={...s,...require(Oe.join(Ct(),u.paramsFile))}}catch(E){throw new C(`Failed to read/open params file error: ${E.message}`)}if(u.params)try{s={...s,...JSON.parse(u.params)}}catch(E){throw new C(`Failed to parse params string error: ${E.message}`)}if(u.sauceUser&&!u.sauceKey||!u.sauceUser&&u.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(u.sauceUser&&u.sauceKey&&(NR(),u.saucelabs={},u.saucelabs.username=u.sauceUser,u.saucelabs.accessKey=u.sauceKey),u.sauceOptions){Tn("--sauce-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(Oe.join(Ct(),u.sauceOptions)),k=E.platformName&&["ios","android"].includes(E.platformName.toLowerCase());if(E.browserName){let j=E.browserName.toLowerCase();j==="microsoftedge"?u.browser="edge":u.browser=j}u.browser==="edge"&&parseFloat(E.version)>=79&&(u.browser="edge-chromium");let L=parseFloat(E.version)<50&&!["dev","beta"].includes(E.version);if(!k&&u.browser==="chrome"&&L)throw new C("The minimum chrome supported version is 50.0");u.saucelabs={...u.saucelabs,...E}}catch(E){throw new C(`Failed to parse saucelabs options file error: ${E.message}`)}}if(u.browserstackUser&&!u.browserstackKey||!u.browserstackUser&&u.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(u.browserstackUser&&u.browserstackKey&&(MR(),u.browserstack={},u.browserstack["browserstack.user"]=u.browserstackUser,u.browserstack["browserstack.key"]=u.browserstackKey),u.browserstackOptions){Tn("--browserstack-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(Oe.join(Ct(),u.browserstackOptions)),k=E.platform&&["mac","android"].includes(E.platform.toLowerCase());if(E.browserName&&(u.browser=E.browserName.toLowerCase()),u.browser==="edge"&&parseFloat(E.browser_version)>=79&&(u.browser="edge-chromium"),!k&&parseFloat(E.browser_version)<50&&u.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");u.browserstack={...u.browserstack,...E}}catch(E){throw new C(`Failed to parse browserstack options file error: ${E.message}`)}}if(u.perfecto={},u.perfectoToken&&(u.perfecto.securityToken=u.perfectoToken),u.perfectoOptions){Tn("--perfecto-options","--custom-capabilities-name or --custom-capabilities-file");try{let E=require(Oe.join(Ct(),u.perfectoOptions)),k={location:"US East",securityToken:u.perfectoToken};u.perfecto={...k,...E}}catch(E){throw new C(`Failed to parse perfecto options file error: ${E.message}`)}}if(u.testobjectSauce={},u.testobjectKey&&(u.testobjectSauce.testobjectApiKey=u.testobjectKey),u.testobjectOptions)try{let E=require(Oe.join(Ct(),u.testobjectOptions)),k={testobjectApiKey:u.testobjectKey};u.testobjectSauce={...k,...E}}catch(E){throw new C(`Failed to parse test object options file error: ${E.message}`)}let l={seaLights:{buildSessionId:u.sealightsBuildSessionId,labId:u.sealightsLabId,testStage:u.sealightsTestStage}};if(u.testOptimization=l,!u.project){let k=await(await Promise.resolve().then(()=>(uc(),Ed))).getProjectId();if(k)u.project=k;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}LR(u.project),O.flags.forceTurboModeIfNeeded.isEnabled({projectId:u.project})&&(u.turboMode=!0),u.testConfig&&(u.testConfig=[u.testConfig].flat()),u.testConfigId&&(u.testConfigId=[u.testConfigId].flat()),u.retries=!u.retries||typeof u.retries=="boolean"?1:Number(u.retries)+1,u.browserTimeout=!u.browserTimeout||typeof u.browserTimeout=="boolean"?60*1e3:u.browserTimeout,u.newBrowserWaitTimeout=!u.newBrowserWaitTimeout||typeof u.newBrowserWaitTimeout=="boolean"?600*1e3:u.newBrowserWaitTimeout*60*1e3,u.getBrowserTimeout||(u.getBrowserTimeout=u.browserTimeout),u.getBrowserRetries||(u.getBrowserRetries=Math.round(u.newBrowserWaitTimeout/u.browserTimeout)),u.getSessionTimeout=Math.max(u.browserTimeout,u.getSessionTimeout),u.driverRequestTimeout=Math.max(u.browserTimeout,u.driverRequestTimeout);let m=!!u.timeout;if(u.timeout=!u.timeout||typeof u.timeout=="boolean"?600*1e3:u.timeout,u.beforeParallel=!u.beforeParallel||typeof u.beforeParallel=="boolean"?1:Number(u.beforeParallel),u.parallel=!u.parallel||typeof u.parallel=="boolean"?1:Number(u.parallel),u.afterParallel=!u.afterParallel||typeof u.afterParallel=="boolean"?1:Number(u.afterParallel),u.tunnelPort=!u.tunnelPort||typeof u.tunnelPort=="boolean"?"80":u.tunnelPort,u.port&&=Number(u.port),!u.token){let k=await(await Promise.resolve().then(()=>(uc(),Ed))).getToken();if(k)u.token=k;else throw new C("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let p=E=>E<=0||!Number.isInteger(E);if(p(u.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(u.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(p(u.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(p(u.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(p(u.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(p(u.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(p(u.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(p(u.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(u.mode&&![J.EXTENSION,J.SELENIUM,J.APPIUM].includes(u.mode))throw new C(`runner mode <${u.mode}> is not supported`);if(u.browser&&![...Ur,...en].includes(u.browser))throw new C(`browser ${u.browser} is not supported`);if(u.mode!==J.SELENIUM&&u.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(u.appiumLogLevel||(u.appiumLogLevel="silent"),!DR.has(u.appiumLogLevel))throw new C(`runner appium-log-level <${u.appiumLogLevel}> is not supported`);if(u.testPlan&&u.testPlan.length===0&&u.testPlanId&&u.testPlanId.length===0){if(typeof u.host!="string"&&typeof u.grid!="string"&&typeof u.gridId!="string"&&!u.localTmaUrl&&!u.useLocalChromeDriver&&!u.useChromeLauncher&&!u.createPrefechedData&&!u.printGrids)throw new C("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(u.testId.length||u.label.length||u.name.length||o||u.browser||c||u.localTmaUrl||u.useLocalChromeDriver||u.useChromeLauncher)throw new C("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!a&&(u.beforeParallel!==1||u.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([u.host,u.grid,u.gridId].filter(Boolean).length>1)throw new C("please define exactly one of --grid or --grid-id or --host");if((G=u.host)!=null&&G.includes("/")&&(/^(f|ht)tps?:\/\//i.test(u.host)||(u.host=`http://${u.host}`),u.host=ew.parse(u.host).hostname),u.resultLabel.length){u.resultLabel=u.resultLabel.map(k=>k.trim()).filter(Boolean);let E=u.resultLabel.filter(k=>k.length>=250).filter(Boolean);if(u.branch==="auto-detect"&&u.resultLabel.includes("auto-detect-branch")&&Er()&&u.resultLabel.unshift(Er()),E.length)throw new C("A result label cannot exceed 250 characters")}let h=Bo(u);if(!u.w3cCapabilities&&!u.oldCapabilities)throw new C("cannot set --w3c-capabilities and --old-capabilities options as false");if(u.protocol||=u.port===443?"https":"http",!["http","https"].includes(u.protocol))throw new C("invalid --protocol value, allow --protocol http or https");if(u.rerunFailedByRunId&&u.branch)throw new C("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(u.rerunFailedByRunId&&(c||u.name.length||u.testId.length||u.label.length||a))throw new C("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(u.setRetention&&!At.inRange(At.parseInt(u.setRetention),1,11))throw new C("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");u.setRetention&&=Number(u.setRetention);let g="is no longer supported, please use --override-mapping-file";if(u.mockNetworkHar)throw new C(`--mock-network-har ${g}`);if(u.mockNetworkPattern)throw new C(`--mock-network-pattern ${g}`);if(u.disableMockNetwork&&u.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!u.collectCodeCoverage&&u.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(u.collectCodeCoverage&&u.codeCoverageReporter&&At.difference(u.codeCoverageReporter,xd).length){let E=At.difference(u.codeCoverageReporter,xd);throw new C(`invalid --code-coverage-reporter parameters ${E.join("/")}`)}u.codeCoverageReporter=u.codeCoverageReporter.length===0?["html","text"]:u.codeCoverageReporter,u.codeCoverageInclude=u.codeCoverageInclude.length===0?["src/**"]:u.codeCoverageInclude;let b={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},T=Object.keys(b).filter(E=>!!u[E]);if([J.APPIUM,J.SELENIUM].includes(u.mode)&&T.length){let E=T.length>1?"are":"is";throw new C(`${T.map(k=>b[k]).join(" and ")} ${E} only applicable in extension mode`)}if((u.useChromeLauncher||u.useLocalChromeDriver)&&(u.browser="chrome"),u.tmsFieldFile)try{let E=pc.readFileSync(u.tmsFieldFile);u.tmsCustomFields=JSON.parse(E)}catch(E){throw new C(`failed to parse field file error: ${E.message}`)}if(u.applyIntersectionsToBeforeAndAfterSections&&!u.intersectWithLabel&&!u.intersectWithSuite&&!u.intersectWithSuiteId)throw new C("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(u.labelIntersectionOperand===!0)throw new C("The --label-intersection-operand flag requires a value. Please provide a value after the flag.");if(u.labelIntersectionOperand&&!Object.values(si).includes(u.labelIntersectionOperand))throw new C(`The --label-intersection-operand flag must be one of the following values: ${Object.values(si).join(", ")}`);if(u.labelIntersectionOperand&&At.isEmpty(u.intersectWithLabel))throw new C("The --label-intersection-operand flag must be used together with the --intersect-with-label flag.");if(u.highSpeed&&(Tn("--high-speed","--turbo-mode"),u.turboMode=!0),u.skipLoadBalancer&&!u.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(u.deviceUdid&&(u.deviceName||u.osVersion))throw new C("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(u.setNoReset&&u.fullReset)throw new C("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(u.lightweightMode)try{let E={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},k=typeof u.lightweightMode=="string"?JSON.parse(u.lightweightMode):{};u.lightweightMode={...E,...k}}catch(E){throw new C(`failed to parse lightweightMode settings error: ${E.message}`)}else u.turboMode&&![J.APPIUM,J.SELENIUM].includes(u.mode)?u.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:u.turboMode&&[J.APPIUM,J.SELENIUM].includes(u.mode)&&console.warn(`
|
|
410
|
+
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof u.baseUrl=="boolean")throw new C("base url cannot be used as a flag, and must contain a string value");return{testId:[u.testId].flat(),name:[u.name].flat(),label:[u.label].flat(),suites:[u.suite].flat(),suiteIds:[u.suiteId].flat(),testPlan:[u.testPlan].flat(),testPlanIds:[u.testPlanId].flat(),reportFile:u.reportFile,urls:u.urls,reportFileClassname:u.overrideReportFileClassname,reporters:u.reporters,project:u.project,host:u.host,headless:u.headless,localTmaUrl:u.localTmaUrl,useLocalChromeDriver:u.useLocalChromeDriver,chromeBinaryLocation:u.chromeBinaryLocation,useChromeLauncher:u.useChromeLauncher,port:u.port,grid:u.grid,gridId:u.gridId,disableNativeEvents:u.disableNativeEvents,saucelabs:u.saucelabs,browserstack:u.browserstack,baseUrl:u.baseUrl,branch:(u.branch==="auto-detect"?Er():u.branch)||"master",autoDetect:u.branch==="auto-detect",token:u.token,userAccessKey:u.userAccessKey,userParamsData:s,mode:u.mode,browser:u.browser,beforeParallel:u.beforeParallel,parallel:u.parallel,afterParallel:u.afterParallel,canary:u.canary,rerunFailedByRunId:u.rerunFailedByRunId,disableGridCheck:u.disableGridCheck,disableTimeoutRetry:u.disableTimeoutRetry,resultLabels:u.resultLabel,path:u.path,protocol:u.protocol,perfecto:u.perfecto,experitestToken:u.experitestToken,testobjectSauce:u.testobjectSauce,testOptimization:u.testOptimization,gridUsername:u.gridUsername,gridPassword:u.gridPassword,overrideExecutionName:u.overrideExecutionName,tmsSuppressReporting:!!u.suppressTmsReporting||!!u.tmsSuppressReporting,tmsRunId:u.tmsRunId,tmsCustomFields:u.tmsCustomFields,proxyForGrid:u.proxyForGrid,retentionDays:u.setRetention,passZeroTests:!!u.passZeroTests,runQuarantinedTests:!!u.runQuarantinedTests,deviceName:u.deviceName,deviceUdid:u.deviceUdid,customTag:u.customTag,osVersion:u.osVersion,duration:u.duration,skipLoadBalancer:u.skipLoadBalancer,lockDevice:u.lockDevice,appId:u.appId,appiumLogLevel:u.appiumLogLevel,setNoReset:u.setNoReset,fullReset:u.fullReset,ext:u.ext,extensionPath:u.extensionPath,extensionLocation:[u.extensionPath].filter(Boolean),playerLocation:u.playerPath||h,playerPath:u.playerPath,playerRequirePath:u.playerRequirePath,tunnel:u.tunnel,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,externalLambdatestTunnelId:u.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:u.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:u.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:u.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:!!u.externalLambdatestDisableAutomationTunneling,externalLambdatestMitm:!!u.externalLambdatestMitm,beforeTest:u.beforeTest,afterTest:u.afterTest,beforeSuite:u.beforeSuite,afterSuite:u.afterSuite,timeout:u.timeout,timeoutWasGiven:m,browserTimeout:u.browserTimeout,newBrowserWaitTimeout:u.newBrowserWaitTimeout,getBrowserTimeout:u.getBrowserTimeout,getBrowserRetries:u.getBrowserRetries,getSessionTimeout:u.getSessionTimeout,getSessionRetries:u.getSessionRetries,driverRequestTimeout:u.driverRequestTimeout,driverRequestRetries:u.driverRequestRetries,testStartTimeout:u.testStartTimeout,testConfigNames:u.testConfig,testConfigIds:u.testConfigId,overrideMappingFile:u.overrideMappingFile,disableMockNetwork:u.disableMockNetwork,codeCoverageUrlFilter:u.codeCoverageUrlFilter,collectCodeCoverage:u.collectCodeCoverage,codeCoverageReportPath:u.codeCoverageReportPath,codeCoverageSourceMapPath:u.codeCoverageSourceMapPath,codeCoverageReporter:u.codeCoverageReporter,codeCoverageInclude:u.codeCoverageInclude,executionId:u.executionId,remoteRunId:u.remoteRunId,schedulerId:u.schedulerId,source:u.source,resultId:u.resultId,installCustomExtension:u.installCustomExtension,w3cCapabilities:u.w3cCapabilities,oldCapabilities:u.oldCapabilities,chromeBlockLocation:u.chromeBlockLocation,chromeUserDataDir:u.chromeUserDataDir,retries:u.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:u.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:u.monitorPerformance,user:u.user,lightweightMode:u.lightweightMode,createPrefechedData:u.createPrefechedData,saveRCALocally:u.saveRcaLocally,exitCodeIgnoreFailingTests:u.exitCodeIgnoreFailingTests,disableSockets:u.disableSockets,intersections:{labels:u.intersectWithLabel.length?[u.intersectWithLabel].flat():void 0,suiteNames:u.intersectWithSuite.length?[u.intersectWithSuite].flat():void 0,suiteIds:u.intersectWithSuiteId.length?[u.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:u.applyIntersectionsToBeforeAndAfterSections,labelIntersectionOperand:u.labelIntersectionOperand},testDataFileName:u.testData,downloadBrowser:u.downloadBrowser,slotService:"mongo",printGrids:u.printGrids,printFinalCaps:u.printFinalCaps,customCapabilities:i,customCapabilitiesName:u.customCapabilitiesName}}});var Pt,Od,nw,_d,ow,mc,UR,BR,kd,jR,fc,Pd,$R,gc,wn,WR,VR,aw,cw,lw=I(()=>{"use strict";Pt=R(require("node:os")),Od=R(require("node:path")),nw=R(require("portfinder")),_d=R(require("node:fs")),ow=R(require("node:child_process"));U();ye();W();mc=A("testimCloudflare"),UR="https://github.com/cloudflare/cloudflared/releases/download/2025.11.1/",BR={win32ia32:{path:"cloudflared-windows-386.exe",sha256:"1e76c0d4e6ff2576db46ad1a7397415729fbaf886b22aa49327f66185a2e8fc8"},win32x64:{path:"cloudflared-windows-amd64.exe",sha256:"413f9b24dc6e61a455564651524f167b8ce29ac4ccd40703dea7af93cd37ed39"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",sha256:"155a288fef19dba08f0c7145c16a207baf137462d8a1289a78bf8564f9e51244",extract:!0},darwinarm64:{path:"cloudflared-darwin-arm64.tgz",sha256:"45cfbb59a720f60b873906aa6469f8c4058f26be6d351c3e2920bc9cb4714273",extract:!0},linuxia32:{path:"cloudflared-linux-386",sha256:"bec7a150d54d5c9e950ed41b434678f302698ad4638693ac9166ad186e4bb945"},linuxx64:{path:"cloudflared-linux-amd64",sha256:"991dffd8889ee9f0147b6b48933da9e4407e68ea8c6d984f55fa2d3db4bb431d"}},kd=Pt.tmpdir(),jR=Pt.platform()==="win32"?"cloudflared.exe":"cloudflared",fc=Od.join(kd,jR),Pd=6e4,$R=500,gc=null,wn=null,WR=async(s,e)=>{let t=`http://localhost:${e}/metrics`,r=new Promise((o,a)=>{s.on("error",c=>{let l=`Cloudflare tunnel process error: ${c.message}`;mc.error(l,{error:c}),a(new Error(l))}),s.on("exit",c=>{if(c!==0){let l=`Cloudflare tunnel exited with code ${c}`;mc.error(l,{code:c}),a(new Error(l))}})}),i=async()=>{for(;;){try{let c=(await(await fetch(t)).text()).match(/cloudflared_tunnel_ha_connections\s+(\d+)/);if(c&&Number(c[1])>=1)return}catch{}await ie($R)}},n=ie(Pd).then(()=>{let o=`Cloudflare tunnel connection timeout after ${Pd} seconds`;throw mc.error(o,{timeout:Pd}),new Error(o)});await Promise.race([i(),r,n])},VR=async()=>{if(await Te(fc))return;let e=BR[Pt.platform()+Pt.arch()];if(!e){let r=`tunnel on ${Pt.platform()+Pt.arch()} platform is not supported.`;throw mc.error(r,{platform:Pt.platform()+Pt.arch()}),new Error(r)}let t=e.extract?Od.join(kd,e.path):fc;await Xe(`${UR}/${e.path}`,t),await ol(t,e.sha256),e.extract&&await sl(t,kd),await _d.promises.chmod(fc,"755")},aw=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([od(s.company.companyId,t),VR()]);gc=r._id;let i=await nw.getPortPromise({port:9e3});wn=ow.spawn(fc,["--metrics",`localhost:${i}`,"tunnel","--no-autoupdate","run","--protocol","http2","--token",r.token],{stdio:["ignore","pipe","pipe"]}),await WR(wn,i),await ad(s.company.companyId,gc),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await _d.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},cw=async s=>{let e=[];return gc&&e.push(cd(s.company.companyId,gc)),wn&&e.push(new Promise((t,r)=>{wn.on("close",i=>{i&&r(new Error(`tunnel process exited with code ${i}`)),t()}),wn.kill()})),await Promise.all(e)}});var Dd={};q(Dd,{connect:()=>hc,disconnect:()=>yc,serveTunneling:()=>HR});var uw,Ld,pw,fr,hc,yc,HR,Nd=I(()=>{"use strict";Ni();lw();uw=R(require("ora"));W();oe();Wo();Ld=A("tunnel"),pw=s=>{var e;return[N.TESTIM_LAMBDATEST,N.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"&&s.gridData.tunnelUser&&s.gridData.tunnelUser.length>0&&s.gridData.tunnelKey&&s.gridData.tunnelKey.length>0},fr=(s,e,t)=>{var r,i,n;return Ld.info(`${t} tunnel, status: ${s}`,{companyId:(r=e.company)==null?void 0:r.companyId,projectId:(i=e.projectData)==null?void 0:i.projectId,testId:e.testId,desiredTunnel:(n=e.gridData)==null?void 0:n.tunnel,actualTunnel:t})},hc=async s=>{if(!s.tunnel)return;let e,t=null;try{e=(0,uw.default)("Starting tunnel...").start(),pw(s)?(t="lambdatest",fr("connecting",s,t),await Jt.connectTunnel(s),fr("connected",s,t)):(t="cloudflare",fr("connecting",s,t),await aw(s),fr("connected",s,t)),e.succeed()}catch(r){let i="Failed to start tunnel. Please contact support@testim.io";throw r.isInvalidCredsForLT&&(i="Could not connect to LambdaTest. Check your credentials and then try again."),Ld.error("Failed to open tunnel",{err:r}),e==null||e.fail(i),new Error(r.isInvalidCredsForLT?`${i}
|
|
411
|
+
${r.stdoutResult}`:i)}},yc=async s=>{if(!s.tunnel)return;let e=null;try{pw(s)?(e="lambdatest",fr("disconnecting",s,e),await Jt.disconnectTunnel(s),fr("disconnected",s,e)):(e="cloudflare",fr("disconnecting",s,e),await cw(s),fr("disconnected",s,e))}catch(t){let r="catch error - failed to close tunnel";throw Ld.error(r,{err:t}),new Error(r)}},HR=async(s,e=new Promise(()=>{}))=>(await hc(s),ys(()=>yc(s)),await e)});var gw={};q(gw,{init:()=>hx,run:()=>dx});async function zR(s){let e=s.project,t=await id(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),ds(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Xs}function JR(s,e){var n,o,a,c,l,d,m,p,f,h,g,b,T;let t=Xn(e.activePlan),r=s.parallel;if(t==="free"&&r>mw)throw new C(`The free plan allows only ${mw} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let v=(n=s.projectData)!=null&&n.type?KR[s.projectData.type]:void 0,y=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&v?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[v]:0;y&&r>y&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${y}).
|
|
412
|
+
We'll use the maximum of ${y} for now. To use more, you can adjust your command or upgrade your plan.`),s.parallel=y);let w=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.tunnel;if(s.tunnel&&!w)throw new C("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let S=(m=(d=e.activePlan)==null?void 0:d.premiumFeatures)==null?void 0:m.runInTurboMode;s.lightweightMode&&!S&&(console.warn(`
|
|
413
|
+
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((p=s.gridData)==null?void 0:p.type)===N.TESTIM_TVC){let v=e.tvcLicense.expireAt||1;if(Date.now()>v&&!e.churnedByL2C)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let y=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>y)throw new C(`Your license allows only ${y} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((g=s.gridData)==null?void 0:g.type)===N.TESTIM_TDC){let v=e.tdcLicense.expireAt||1;if(Date.now()>v)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let i=s.retentionDays;if(i){let v=(T=(b=e.activePlan)==null?void 0:b.premiumFeatures)==null?void 0:T.resultRetention;if(i>v)throw new C(`Retention days (${i}) cannot be greater than the company's retention days (${v}). Run aborted`)}if(ir(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let v=e.tvcLicense,y=e.tdcLicense;if(v!=null&&v.isPaid||y!=null&&y.isPaid)return;let w=e==null?void 0:e.createdAt;if(new Date(w)<new Date(O.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let x=s.retries;x&&x>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function XR(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await zR(s)}catch(t){if([C,Xs].some(r=>t instanceof r))throw t;Md.error("could not validate cli account",{err:t})}}function YR(s){let e=Si();return dg({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function QR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(O.flags.useNewWSCLI.isEnabled()&&!e&&!t)return It.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Zo(),cy));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(ea(),py));r.init(s)}}function ZR(s,e){let{branch:t,autoDetect:r}=s;if(lg(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function ex(s,e){let{id:t,type:r}=e,n=fw.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=xi();n&&(s.sfdcCredential=await sd({projectId:t,branch:o}))}async function tx(s){if(!s.testDataFileName)return;let{testDataFileName:e}=s,t;try{t=(await rd(`fileName=${e}&action=download&fileType=test-data&projectId=${s.project}`)).s3Url;let n=await(await fetch(t)).json();pt("test-data-file-used-in-cli",{projectId:s.project,testDataFileId:e,source:s.source}),s.testDataFileName=e,s.testDataString=n.testData}catch(r){let i=t?`, s3Url: ${t}`:"";throw new C(`Failed to read/open test data file error: ${r.message}${i}`)}}function rx(s,e){let{id:t,name:r,activePlan:i={}}=e,n=!!i.isPoc,o=!!i.isStartUp,a=Xn(i);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<dw?dw:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(n),O.setIsStartUp(o),O.setPlanType(a),Nt.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:n,isStartUp:o,activePlan:i}}function sx(s,e){s.editorUrl=st||e}function ix(s,e){s.allGrids=e}function nx(s,e){s.authData=e}function ox(s,e){let{id:t,name:r,type:i,defaults:n}=e;O.setProjectId(t),O.setProjectType(i),s.projectData={projectId:t,type:i,name:r,defaults:n}}async function ax(s){var e;s.gridData=await og(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function cx(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function lx(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(pt("user-override-file",t),s.mockNetworkRules=await MT(s.overrideMappingFile))}async function ux(s){if(s.customCapabilitiesName){let e=await ud(s.project,s.customCapabilitiesName);if(!e)throw new C(`"${s.customCapabilitiesName}" custom capabilities not found`);s.customCapabilities=e.capabilities}}async function px(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:i,useChromeLauncher:n}=s;r||(s.source=i||n?"cli-local":"cli"),await XR(s),M("in runRunner before tunnel.connect"),await hc(s),M("in runRunner after tunnel.connect");let a=await new Us(e).run(s);return M("before tunnel.disconnect"),await yc(s),await gx(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function mx(s){var e;Nt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
|
|
414
414
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
415
415
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
416
|
-
`)}function
|
|
417
|
-
Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://docs.tricentis.com/testim/content/testops/turbo-mode.htm`),
|
|
416
|
+
`)}function fx(s,e,t){s==="redis"&&_i.start(t,e),s==="mongo"&&Ii.start(e)}async function gx(s,e,t){s==="redis"&&await _i.end(t,e),s==="mongo"&&await Ii.end(e)}async function hx(s){var h,g,b,T,v,y;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:i,disableSockets:n}=s,o=QR(e,{disableResults:n||!!(t!=null&&t.disableResults&&(r||i===J.SELENIUM)),disableRemoteStep:n||!!(t!=null&&t.disableRemoteStep)});o.catch(()=>{});let{authData:a,companyByProjectId:c,projectById:l,branchName:d,allGrids:m,clientConfig:p}=await bn(s);if(c.disabled)throw new C("The company is disabled.");if(l.disabled)throw new C("The project is disabled.");if(s.printGrids){let w=m.sort((S,x)=>S.type.localeCompare(x.type));console.table(w.reduce((S,x)=>{class _{constructor(E,k){this.Type=E,this.Browsers=k}}let B=Object.entries(x.browsers||{"N/A":""}).map(G=>G.join(":")).join(", ");return S[x.name]=new _(x.type,B),S},{})),process.exit(0)}if(await o,M("after featureFlagsReady and socketConnected"),sx(s,p.editorUrl),rx(s,c),ox(s,l),cx(s,l),ZR(s,d),ix(s,m),nx(s,a),await tx(s),await ex(s,l),await ax(s),await ux(s),JR(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[oh(s)]),O.flags.clearRunnerFileCache.isEnabled())try{await os(),Md.info("runner file cache cleared")}catch(w){Md.error("failed to clear runner file cache",{err:w})}(g=s.lightweightMode)!=null&&g.disableLabs||await Ji.loadLabFeatures(l.id,c.activePlan),((b=s.lightweightMode)==null?void 0:b.type)==="turboMode"&&(O.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((T=s.lightweightMode)==null?void 0:T.type)==="turboMode"&&console.log(`
|
|
417
|
+
Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://docs.tricentis.com/testim/content/testops/turbo-mode.htm`),fx(s.slotService,e,c.id),YR(e),await lx(s),mx(s);let f=xi();await Z.setOptions(s,f),(y=(v=s.testOptimization)==null?void 0:v.seaLights)!=null&&y.testStage&&s.testOptimization.seaLights.testStage!==qR&&ds(a.uid,"cli-sealights_stage_changed",{testStage:s.testOptimization.seaLights.testStage,projectId:e})}var fw,dw,mw,qR,Md,KR,dx,hw=I(()=>{"use strict";fw=R(require("lodash"));U();Nd();je();ps();hs();Ar();Kl();ye();wt();zt();W();Mt();le();oe();Q();Jp();Yo();$u();pe();ki();fd();Wi();dw=1800*1e3,mw=1,qR="Testim Automation",Md=A("runner");KR={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};dx=px});function yw(s){s.get("/",(e,t)=>{let r=Fd();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:oc()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());Sd({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var bw=I(()=>{"use strict";uc();Ud();pd()});var Bd,Tw,gr,bc,ww=I(()=>{"use strict";Bd=R(require("chalk"));As();Tw=require("express");W();Q();wl();gr=A("cli-router"),bc=(0,Tw.Router)();bc.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:i,context:n,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!i||!n||!o||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}if(i.nodePackageParams){let p=i.nodePackageParams.map(h=>h.testimPackageLocalLocation).filter(Boolean),f=Tl(p);if(f){gr.error("Invalid package paths detected",{invalidPaths:f,stepId:r,testResultId:o}),e.status(400).json({success:!1,code:"invalid-package-path",message:`Invalid package path(s) detected: ${f.join(", ")}`});return}}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d,nodePackageParams:i.nodePackageParams};try{let p=await Cs(t,r,i,n,o,a,c,l,d);p.success||(console.log(Bd.default.red(p.result.resultValue)),gr.error("CLI Action Failure",{message:p.result.resultValue,...m})),e.status(200).json({success:!0,data:p})}catch(p){gr.error("failed to run cli code",{err:p,...m}),console.log(Bd.default.red("failed to run cli code",p)),e.status(500).json({success:!1,code:"internal-error"})}});bc.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:i,packageData:n,stepResultId:o,timeout:a}=s.body;if(!t||typeof n!="object"||!r||typeof i!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let c=bl(n);if(c){gr.error("Invalid package names detected",{invalidNames:c,stepId:t,testResultId:r}),e.status(400).json({success:!1,code:"invalid-package-name",message:`Invalid package name(s): ${c.join(", ")}`});return}let l={stepId:t,testResultId:r,retryIndex:i,stepResultId:o,timeout:a,packageData:n};try{let d=await xs(t,r,i,n,o,a);gr.info("installed packages successfully",l),e.status(200).json({success:!0,data:d})}catch(d){if(d instanceof _t){gr.error("failed to install node packages",{err:d,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:d.message});return}if(d instanceof ue){gr.error("timeout installing node package",{err:d,...l}),e.status(200).json({success:!1,code:"timeout"});return}gr.error("failed to install node packages",{err:d,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var vw=I(()=>{"use strict";ww()});var Rw={};q(Rw,{orchestrateRoutes:()=>yx});function yx(s){let e=(0,Ew.default)();e.disable("x-powered-by"),s(e),e.use(jd.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,Iw.default)()),e.use(jd.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:Fe||Yd?"*":["chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia"]};return e.use("*",(0,Sw.default)(r)),yw(e),e.use("/cliJs",bc),e.use((i,n)=>{n.status(404).send("Endpoint Not Found")}),e}var Sw,Ew,jd,Iw,xw=I(()=>{"use strict";Sw=R(require("cors")),Ew=R(require("express")),jd=R(require("body-parser")),Iw=R(require("compression"));bw();vw();le()});var Aw={};q(Aw,{init:()=>bx});async function bx({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:i}=await Promise.resolve().then(()=>(xw(),Rw));return new Promise((n,o)=>{let a=()=>{};t&&(Qf(t,r),a=p=>{p.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let c=i(a),l=Cw.createServer(c);l.listen(s,e),l.on("error",d),l.on("listening",m);function d(p){if(p.syscall!=="listen")return o(p);switch(p.code){case"EACCES":case"EPERM":return o(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new C(`Port ${s} is already in use, is another Testim instance running?`));default:return o(p)}}function m(){let{port:p}=l.address();console.log(`Running on port: ${p}`),Tx()}})}async function Tx(){await require("prompts")({name:"",type:"text",message:'Type the word "stop" or Press Ctrl + C.',validate:t=>t.toUpperCase().trim()==="STOP"}),console.log("Exiting Testim CLI"),process.exit(0)}var Cw,Pw=I(()=>{"use strict";Cw=R(require("http"));wt();Q()});var Mw={};q(Mw,{getStartedWithStart:()=>Fd,runAgentMode:()=>Ex});async function Ex(s){var r;let e;if(await Rr(s.playerLocation,s.canary),s.startTestimBrowser){await xx();try{e=await Rx(s)}catch(i){throw(r=i==null?void 0:i.message)!=null&&r.includes("user data directory is already in use")?new C('Please close all chrome browsers that were opened with "testim start" and try again'):i}}let t=await Promise.resolve().then(()=>(Pw(),Aw));return e!=null&&e.webdriverApi&&setTimeout(()=>{setTimeout(()=>(Ip(),Me(zb)))},6e3),t.init(s)}function Fd(){return Dw}function kw(s){try{return process.kill(s,0)}catch{return!1}}async function Ix(s,e,t){let r=hr.join(Tt,`chrome-${yi}-process`),i=3e3,n=()=>{_e.rmSync(r,{recursive:!0}),console.log(`
|
|
418
418
|
|
|
419
|
-
Browser session ended`),process.exit(0)};if(await Te(
|
|
420
|
-
`).map(
|
|
421
|
-
`):""}overrideMimeType(t){if([de.LOADING,de.DONE].includes(this.readyState))throw new
|
|
422
|
-
${
|
|
419
|
+
Browser session ended`),process.exit(0)};if(await Te(r)){let f=JSON.parse(_e.readFileSync(r));if(kw(f.pid)){let h=()=>kw(f.pid)?setTimeout(h,i):n();return h(),{webdriverApi:f}}}let o=await uo();await Te($s)||await _e.promises.mkdir($s,{recursive:!0});let c=[...Nw($s,e,t,o).desiredCapabilities.chromeOptions.args,...wc.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],l={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=s.extensionPath?"http://localhost:3000/app/":new URL("?startMode=true",st||Tr).href,m=await wc.launch({chromeFlags:c,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:$s,chromePath:o,envVars:l}),p={port:m.port,pid:m.pid,cdpUrl:await Ir(`localhost:${m.port}`)};return _e.writeFileSync(r,JSON.stringify(p)),m.process.once("exit",n),m.process.once("close",n),{webdriverApi:p}}async function Rx(s){let e=`${Zt}/testim-full-master.zip`,t=hr.basename(e),r=hr.join(Tt,t),i=hr.join(Tt,`${t}__unzipped__`),n=!(s.ext||s.extensionPath);if(n&&await Te(r)){let f=await _e.promises.stat(r);n=Date.now()-vx>f.mtimeMs}if(await _e.promises.mkdir(Tt,{recursive:!0}),n){let f=(0,_w.default)("Downloading Testim Editor").start();await Xe(e,r);try{await Ye(r,i)}catch{await _e.promises.rm(r,{recursive:!0,force:!0}),await Xe(e,r);try{await Ye(r,i)}catch{throw await _e.promises.rm(r,{recursive:!0,force:!0}),f.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await _e.promises.rm(i,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await _e.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await Ix(s,o,i);await mi({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=Nw($s,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=(Ki(),Me(Wh)),{SeleniumPerfStats:l}=(Ts(),Me(Zg)),d=new c;d.seleniumPerfStats=new l;let m=await d.initClient(a);Dw=!0;let p=`${s.extensionPath?"http://localhost:3000/app/":st||Tr}?startMode=true`;await d.url(p),Object.assign(d,{initialUrl:p});try{d.cdpUrl=await Ir(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function Nw(s,e,t,r){let i=e?[e]:[],n=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];t&&n.push(`--load-extension=${t}`);try{let o=Go();o.length&&o.forEach(a=>n.push(`--disable-features=${a}`))}catch{}return{logLevel:wx,desiredCapabilities:{chromeOptions:{args:n,extensions:i,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function xx(){if(await Te(Tc))try{let{webSocketDebuggerUrl:s}=await Cx();await Ax(s),await _e.promises.unlink(Tc)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await _e.promises.unlink(Tc)}}async function Cx(){let s=await _e.promises.readFile(Tc,{encoding:"utf8"}),[e,t]=s.split(`
|
|
420
|
+
`).map(n=>n.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let i=await Ir(`localhost:${r}`,500);if(!i.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:i}}async function Ax(s,e=100){let t=await Px(s,e);return sr(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function Px(s,e=100){let t=Ya({timeout:e}),r=new Lw.default(s,t),i=sr(o=>{r.once("open",o)}).then(()=>{r.removeAllListeners()}),n=sr(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return Promise.race([i,n]).then(()=>r)}var Ow,_w,Lw,_e,hr,wc,wx,vx,$s,Sx,Tc,Dw,Ud=I(()=>{"use strict";Ow=R(require("ms")),_w=R(require("ora")),Lw=R(require("ws")),_e=R(require("node:fs")),hr=R(require("node:path")),wc=R(require("chrome-launcher"));le();gi();Q();Fl();U();qo();Qa();wx=_n?"verbose":"silent",vx=(0,Ow.default)("1h"),$s=hr.join(Tt,"profile"),Sx="DevToolsActivePort",Tc=hr.join($s,Sx);Dw=!1});var ZM=require("source-map-support/register");var Pn=R(require("os")),Vs=R(require("url")),Hs=R(require("http")),Ec=R(require("https")),En=R(require("form-data")),In=class{constructor(){this.onloadstart=null;this.onprogress=null;this.onabort=null;this.onerror=null;this.onload=null;this.ontimeout=null;this.onloadend=null;this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]||=[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var i;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let n of r)n==null||n.call(this,e);(i=this[`on${t}`])==null||i.call(this,e)}},Rn=class extends In{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(t!=null)if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),i=new Uint8Array(t);for(let n=0;n<t.byteLength;n++)r[n]=i[n];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),i=t.byteOffset,n=new Uint8Array(t.buffer);for(let o=0;o<t.byteLength;o++)r[o]=n[o+i];this._body=r}else if(typeof t=="object"&&t instanceof En.default)this._body=null;else throw new Error(`Unsupported send() data ${t}`)}_finalizeHeaders(t,r){this._contentType&&!("content-type"in r)&&(t["Content-Type"]=this._contentType),this._body&&(t["Content-Length"]=this._body.length.toString())}_startUpload(t){this._body&&t.write(this._body),t.end()}},Ws=class{constructor(e){this.type=e;this.target=null;this.currentTarget=null;this.lengthComputable=!1;this.loaded=0;this.total=0;this.bubbles=!1;this.cancelable=!1}},xn=class extends Error{},Cn=class extends Error{},An=class extends Error{},yr=class extends Error{},de=class de extends In{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Hs.globalAgent;this.nodejsHttpsAgent=Ec.globalAgent;this.nodejsBaseUrl=null;this._restrictedMethods={CONNECT:!0,TRACE:!0,TRACK:!0};this._restrictedHeaders={"accept-charset":!0,"accept-encoding":!0,"access-control-request-headers":!0,"access-control-request-method":!0,connection:!0,"content-length":!0,cookie:!0,cookie2:!0,date:!0,dnt:!0,expect:!0,host:!0,"keep-alive":!0,origin:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,via:!0};this._privateHeaders={"set-cookie":!1,"set-cookie2":!1};this._userAgent=`Mozilla/5.0 (${Pn.type()} ${Pn.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=de.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new Rn(this);this._method=null;this._url=null;this._sync=!1;this._headers=null;this._loweredHeaders=null;this._mimeOverride=null;this._request=null;this._response=null;this._responseParts=null;this._responseHeaders=null;this._aborting=null;this._error=null;this._loadedBytes=0;this._totalBytes=0;this._lengthComputable=!1;this._anonymous=t==null?void 0:t.anon}static nodejsSet(t){de.prototype.nodejsSet(t)}nodejsSet(t){if("httpAgent"in t&&(this.nodejsHttpAgent=t.httpAgent),"httpsAgent"in t&&(this.nodejsHttpsAgent=t.httpsAgent),"baseUrl"in t){let r=t.baseUrl;if(r!==null&&!Vs.parse(r,!1,!0).protocol)throw new xn("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,i){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new An(`HTTP method ${t} is not allowed in XHR`);let n=this._parseUrl(r);i===void 0&&(i=!0),this._method=t,this._url=n,this._sync=!i,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(de.OPENED),this._request=null,this._response=null,this.status=0,this.statusText="",this._responseParts=[],this._responseHeaders=null,this._loadedBytes=0,this._totalBytes=0,this._lengthComputable=!1}setRequestHeader(t,r){if(this.readyState!==de.OPENED)throw new yr("XHR readyState must be OPENED");let i=t.toLowerCase();this._restrictedHeaders[i]||i.startsWith("sec-")||i.startsWith("proxy-")||(r=r.toString(),i in this._loweredHeaders?(t=this._loweredHeaders[i],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[i]=t,this._headers[t]=r))}send(t){if(this.readyState!==de.OPENED)throw new yr("XHR readyState must be OPENED");if(this._request)throw new yr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new Cn(`XHR request to ${this._url.href} failed: unsupported protocol '${this._url.protocol}'. Please use supported protocols like HTTP, HTTPS, or file.`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var i;let r=t.toLowerCase();return((i=this._responseHeaders)==null?void 0:i[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
|
|
421
|
+
`):""}overrideMimeType(t){if([de.LOADING,de.DONE].includes(this.readyState))throw new yr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new Ws("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new Cn("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(t){if(this._sync)throw new Error("Synchronous XHR processing not implemented");t!=null&&(this._method==="GET"||this._method==="HEAD")?t=null:t||="",this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let r=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,n=(this._url.protocol==="http:"?Hs:Ec).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:r});typeof t=="object"&&t instanceof En.default&&t.pipe(n),this._request=n,this.timeout&&n.setTimeout(this.timeout,()=>this._onHttpTimeout(n)),n.on("response",o=>this._onHttpResponse(n,o)),n.on("error",()=>this._onHttpRequestError(n)),this.upload._startUpload(n),this._request===n&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof En.default&&Object.assign(this._headers,t.getHeaders()),this._headers.Connection="keep-alive",this._headers.Host=this._url.host,this._anonymous&&(this._headers.Referer="about:blank"),this._headers["User-Agent"]=this._userAgent,this.upload._finalizeHeaders(this._headers,this._loweredHeaders)}_onHttpResponse(t,r){if(this._request!==t)return;if([301,302,303,307,308].includes(r.statusCode)){this._url=this._parseUrl(r.headers.location),this._method="GET","content-type"in this._loweredHeaders&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),"Content-Type"in this._headers&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),this._sendHxxpRequest();return}this._response=r,this._response.on("data",n=>this._onHttpResponseData(r,n)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=Hs.STATUS_CODES[this.status],this._parseResponseHeaders(r);let i=this._responseHeaders["content-length"];i?(this._totalBytes=parseInt(i,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(de.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==de.LOADING&&this._setReadyState(de.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(de.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let r=this._request;return this._setError(),r.abort(),this._setReadyState(de.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(de.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(de.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new Ws(t);r.lengthComputable=this._lengthComputable,r.loaded=this._loadedBytes,r.total=this._totalBytes,this.dispatchEvent(r)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let r,i,n,o=this.nodejsBaseUrl===null?t:Vs.resolve(this.nodejsBaseUrl,t),a=Vs.parse(o,!1,!0);return a.hash=null,a.auth&&(n!=null||i!=null)&&(r=a.auth.indexOf(":"),r===-1?n||(n=a.auth):(n||(n=a.substring(0,r)),i||(i=a.substring(r+1)))),(n||i)&&(a.auth=`${n}:${i}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,i])=>{let n=r.toLowerCase();this._privateHeaders[n]||(this._mimeOverride!==null&&n==="content-type"&&(i=this._mimeOverride),this._responseHeaders[n]=i)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),i=new Uint8Array(r);for(let n=0;n<t.length;n++)i[n]=t[n];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}};de.SyntaxError=xn,de.ProgressEvent=Ws,de.SecurityError=An,de.XMLHttpRequest=de,de.InvalidStateError=yr,de.XMLHttpRequestUpload=Rn,de.UNSENT=0,de.OPENED=1,de.HEADERS_RECEIVED=2,de.LOADING=3,de.DONE=4;var Gs=de;Object.assign(global,{xhr2:Gs,XMLHttpRequest:Gs});var Fw=R(require("semver"));je();fd();zt();gi();var $d=R(require("chalk")),Uw=require("node:events");oe();Ni();Q();oe();wo();W();var FT=R(require("os")),gd=R(require("path")),hd=R(require("chalk")),cc=require("fs");le();function UT(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let i=FT.homedir();(0,cc.mkdirSync)(gd.resolve(i,".testim_logs"),{recursive:!0});let n=gd.resolve(i,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${n}`),rm&&console.log(`Call stack: ${s==null?void 0:s.stack}`),(t=s==null?void 0:s.message)!=null&&t.includes("Unable to compile TypeScript")&&((r=s.stack)!=null&&r.includes("runner/src"))&&process.argv.some(o=>o.includes("player-require-path"))&&(console.log(hd.default.red("Looks like you got a TypeScript compile error champ - but it's not a very good one because we use TypeScript in transpile-only mode")),console.log(hd.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,cc.writeFileSync)(n,`${s}
|
|
422
|
+
${s==null?void 0:s.stack}
|
|
423
423
|
|
|
424
|
-
${JSON.stringify(
|
|
424
|
+
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}pi();var SR=A("process-handler"),BT=!1;function ER(s){return s instanceof Error?1:BT?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:i,status:n})=>[t,n].includes(he.SKIPPED)||[t,n].includes(he.FAILED)&&i===Qe.EVALUATING?!1:r!==!0)?1:0)}function IR(){try{or("chromedriver").stop()}catch{}}function jT(){BT=!0}async function yd(s){s!=null&&s.stack&&(ms?console.error(s,s.stack):UT(s)),IR(),await SR.waitForFlush(),process.exit(ER(s))}ye();W();pe();var kx=A("cli-entry");function Ox(s){if(!Fw.satisfies(process.version,s))throw new C(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=20,t=22,r=Number(process.versions.node.split(".")[0]),i=new Date("2026-04-30T00:00:00.000Z"),n=i<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(i);if(r<e)throw new C(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&n)throw new C(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log($d.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function _x(){console.log("Starting Testim.io CLI");let s=await Promise.resolve().then(()=>(U(),Y));M("Starting Testim.io CLI"),Mg(yd);try{Ox(s.getEnginesVersion())}catch(e){console.log("Argument Error:",e.message),process.exit(1)}try{let e=await Promise.resolve().then(()=>(iw(),sw)),{program:t}=e;await O.fetch({proxy:t.proxy}),Vc();let r=await e.process();if(M("in main, after options.process"),jm(global.proxyUri),Uw.EventEmitter.defaultMaxListeners="parallel"in r&&r.parallel>10?r.parallel*3:30,Bm(r.project),Cf("token"in r&&typeof r.token=="string"?r.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(r)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(Mi(),jg));return await o()}if(s.isLoginMode(r))return;if(s.isCreatePrefetchedDataMode(r)){await os(),await bn(r);let{preloadTests:o}=await Promise.resolve().then(()=>(Xo(),ry));await o(r),!r.playerRequirePath&&r.mode!==J.EXTENSION&&await Rr(r.playerLocation,r.canary);let a=await Rf();a.success?console.log(`created prefetched data at ${ro()}`):console.error("failed to create prefetch data",a.error);return}let i=await Promise.resolve().then(()=>(hw(),gw));if(s.isTunnelOnlyMode(r)){await i.init(r);let{serveTunneling:o}=await Promise.resolve().then(()=>(Nd(),Dd));await o(r);return}if(s.isAgentMode(r)){let{runAgentMode:o}=await Promise.resolve().then(()=>(Ud(),Mw));return o(r)}if(r.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(Eu(),sh)),{port:a}=await o(r);r.localRCASaver=`http://localhost:${a}`}r.exitCodeIgnoreFailingTests&&jT(),M("right before testRunner.init/prepareRunner.prepare"),await i.init(r);let n=await NT(r);return M("right after testRunner.init/prepareRunner.prepare"),await i.run(r,n)}catch(e){if(e instanceof qr)return;let t=s.getArgsOnRemoteRunFailure();return t&&await ld({...t,error:e.message}).catch(()=>{}),e instanceof C?(console.log($d.default.red("Argument Error:",e.message)),e):(console.log("Error:",e.message),kx.error("runner ended with unexpected error",{err:e}),e)}}_x().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),yd(s)});
|
|
425
425
|
//# sourceMappingURL=cli.js.map
|