@testim/testim-cli 4.106.0 → 4.107.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.js +51 -51
- package/cli.js.map +3 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/cli.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
${c.msg}`));for(let u of WT)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(i&&!m&&(c.msg=i),d.text=c),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Ie.CoralogixLogger.configure(t),Br.options=t}}});var dc={};G(dc,{getLogger:()=>C,sessionPlayerLoggerFormatter:()=>cc,setExecutionId:()=>lc,setProjectId:()=>uc,setProxyUri:()=>pc});function HT(){let s=[],e=()=>Promise.resolve();if(!_e){let{CoralogixTransport:t}=(oc(),Ne(nc));t.configure(Od);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}if(dd){let t={depth:5,colors:!0};s.push(new mt.transports.Console({format:mt.format.combine(mt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),mt.format.timestamp({format:"HH:mm:ss:SSS"}),mt.format.printf(r=>`[${r.timestamp}] ${r.level} ${r.category}: ${r.message} ${po.inspect(r.meta,t)}`))}))}return[s,e]}function lc(s){ic=s}function uc(s){Ld=s}function pc(s){if(_e||!s)return;let{CoralogixTransport:e}=(oc(),Ne(nc));e.configure({...Od,proxyUri:s})}function Pd(s){return{projectId:Ld,time:new Date().toISOString(),...ic&&!s&&{executionId:ic}}}function C(s){return new ac(YT.child({category:s}))}var kd,mt,po,uo,_d,VT,GT,Od,Cd,cc,qT,zT,KT,JT,YT,ic,Ld,ac,$=w(()=>{"use strict";kd=S(require("os")),mt=S(require("winston"));pe();po=S(require("util")),uo=S(require("chalk")),_d=S(require("dayjs"));B();VT=kd.hostname(),GT=ft(),Od={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};Cd={depth:5,colors:!0},cc=(s,e,t)=>{let r=`[${(0,_d.default)().format("HH:mm:ss:SSS")}]`,n=po.inspect(e,Cd),o=po.inspect(t,Cd);return`${uo.default.white(r)} ${uo.default.reset()}SessionPlayer-${uo.default.red(s)} ${n} ${o}`},[qT,zT]=HT(),KT=md?"debug":"info",JT={release:Boolean(!0),branch:"production"},YT=mt.createLogger({levels:mt.config.syslog.levels,level:KT,transports:qT,defaultMeta:{name:"runner",hostname:VT,nodeVersion:process.version,runnerVersion:GT,...JT}}),ic=null,Ld=null;ac=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Pd(n)})}catch(o){try{this._logger.log("crit",{message:`failed to log message ${o.message}, ${o.stack}`,...Pd(n)})}catch{}}}waitForFlush(){return zT()}}});var ho,jr,P,Jt,fr,Et,mo,$r,oe,Ms,ze,Yt,It,fo,Wr,go,Ns,J=w(()=>{"use strict";ho=require("p-retry"),jr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},P=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Jt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},fr=class extends Error{constructor(t,r){super(t);this.type=r}},Et=class extends ho.AbortError{},mo=class extends ho.AbortError{},$r=class extends ho.AbortError{},oe=class extends Error{},Ms=class extends Error{},ze=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Yt=class extends ze{constructor(){super(...arguments);this.name="GridConcurrencyError"}},It=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},fo=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Wr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},go=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Ns=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function mc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ae(s){return(0,Nd.setTimeout)(s)}function fc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function ce(s,e,t="Timeout Error"){ao&&!Dd&&(Dd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new oe(t);return e=ao?Number(ao)||6e5:e,Promise.race([s,ae(e).then(()=>{throw r})])}async function ie(s,e,{concurrency:t}={}){if(t){Md||=(await import("p-limit")).default;let r=Md(t);return await Promise.all(Array.from(s,(n,o)=>r(()=>e(n,o))))}return await Promise.all(Array.from(s,e))}function Xt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Nd,Dd,Md,gc=w(()=>{"use strict";Nd=require("timers/promises");J();pe();Dd=!1});var Fs,Ud,XT,Us,Fd,QT,ZT,Bd,jd=w(()=>{"use strict";Fs=S(require("lodash"));pe();Ud=require("dns");$();gc();XT=C("http-request-counters"),Us=!1,Fd=async()=>{if(_e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ie(s,t=>Ud.promises.lookup(t)));return e||(Us=!0),e}catch{return XT.error("network connectivity test failed"),Us=!0,!1}},QT=Fs.throttle(Fd,10*1e3),ZT=60*1e3*15,Bd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},ZT)}function t(n,o=n.name){return async function(...i){e(s.call,o);try{let a=await n.call(null,...i);return e(s.success,o),a}catch(a){throw e(s.fail,o),Us||QT(),a}}}async function r(){if(Us||!await Fd())return!1;let n=Fs.sum([...s.fail.values()]),o=Fs.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Us,t}});var Ke={};G(Ke,{deleteFullRes:()=>nw,deleteReq:()=>Bs,didNetworkConnectivityTestFail:()=>Ec,download:()=>vc,get:()=>be,getFullRes:()=>iw,getText:()=>$s,head:()=>aw,isNetworkHealthy:()=>Sc,post:()=>Ve,postForm:()=>js,postFullRes:()=>ow,postText:()=>Tc,put:()=>wc});function tw(){return global.caFileContent}function rw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function sw(){return!Rt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(Rt.default),global.proxyUri}function gr(s,e=!1){let t=tw();t&&s.ca(t);let r=!e&&sw();r&&s.proxy(r)}async function $d(s,e={},t={},r=Vr){let n=Rt.default.delete(s).send(e).timeout(r).set(t);return gr(n),await n}async function yc(s,e,t={},r=Vr,n=0){let o=Rt.default.post(s).send(e).timeout(r).set(t);gr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=s,i.originalRequestTimeout=r,i.additionalSetHeaders=t,i}}async function bc(s,e,t={},r=Vr,{isBinary:n=!1,skipProxy:o=!1}={}){let i=Rt.default.get(s).query(e||{}).timeout(r).set(t);return n&&i.buffer(!0),gr(i,o),await i}var Rt,hc,We,Vr,ew,Dt,Bs,nw,Ve,ow,js,$s,Tc,be,iw,aw,wc,vc,Sc,Ec,Ge=w(()=>{"use strict";Rt=S(require("superagent"));$();jd();hc=C("http-request"),We=Bd(),Vr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,ew=6e4;Dt=(s,e,t)=>{throw hc.error(s,{...t,error:e}),e};Bs=We(async(s,e,t,r)=>{try{let n=await $d(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Dt("failed to delete request",n,{url:s})}});nw=We($d),Ve=We(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await yc(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});ow=We(yc),js=We(async(s,e,t,r={},n=Vr)=>{let o=Rt.default.post(s).type("form").timeout(n).set(r);o.field(e),Object.entries(t).forEach(([i,a])=>{o.attach(i,a.buffer,a.fileName)}),gr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});$s=We(async(s,e,t)=>{try{return(await bc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),Tc=We(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await yc(s,e,t,r,n)).text}catch(o){return Dt("failed to post request",o,{url:s})}}),be=We(async(s,e,t,r,n)=>{try{return(await bc(s,e,t,r,n)).body}catch(o){return Dt("failed to get request",o,{url:s,query:e})}}),iw=We((s,e,t,r)=>bc(s,e,t,r)),aw=We(async s=>{let e=Rt.default.head(s).timeout(Vr);gr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),wc=We(async(s,e,t={},r=Vr)=>{let n=Rt.default.put(s).send(e).timeout(r).set(t);gr(n);try{return(await n).body}catch(o){return Dt("failed to put request",o,{url:s})}}),vc=We(async s=>{hc.info("start to download",{url:s});let e=Rt.default.get(s).timeout(ew).buffer(!0).parse(rw);gr(e);try{let t=await e;return hc.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),Sc=We.isNetworkHealthy,Ec=We.didNetworkConnectivityTestFail});function gt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Mt.resolve(__dirname,"../../"):s=Mt.resolve(__dirname,""),s):process.cwd()}function yo(s,e){return ke(s)?e||Mt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Mt.basename(s)}function ft(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function lw(){try{return ad.node}catch{return""}}async function Gd(s,e,t=!0){let r=await st.promises.readdir(s,{withFileTypes:!0});await st.promises.mkdir(e,{recursive:t});for(let n of r){let o=Mt.join(s,n.name),i=Mt.join(e,n.name);n.isDirectory()?await Gd(o,i):await st.promises.copyFile(o,i)}}async function ge(s){try{return await st.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Mt,Wd,Vd,st,cw,Nt,Je,bo,Ic,nt,Rc,Hd=w(()=>{"use strict";Mt=S(require("path"));Ja();io();Wd=S(require("unzip-stream")),Vd=S(require("p-retry")),st=require("fs"),cw=3;Nt=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Ke));return(0,Vd.default)(()=>e.download(s),{retries:cw,factor:1})},Je=async(s,e)=>{let t=await Nt(s);return st.promises.writeFile(e,t.body)};bo=async(s,e)=>{let t=yo(s,e);return ke(s)?Je(s,t):st.promises.copyFile(s,t)},Ic=async s=>ke(s)?Nt(s):st.promises.readFile(s),nt=async(s,e)=>await(0,st.createReadStream)(s).pipe(Wd.Extract({path:e})),Rc=s=>(0,st.statSync)(s).size/1e6});var Ut={};G(Ut,{APPIUM_SESSION_MESSAGE:()=>kc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>To,MOBILE_RUN_SKIP_REASON:()=>Pc,gridMessages:()=>ht,gridTypes:()=>O,mobileWeb:()=>xc,runnerStatus:()=>Ac,runnerTestStatus:()=>de,socketEventTypes:()=>At,stepResult:()=>Vs,test:()=>Cc,testRunStatus:()=>Ws,testStatus:()=>Ye,timeoutMessages:()=>Ue});var Ue,Ws,Ac,de,Ye,ht,xc,Cc,At,q,O,Vs,To,Pc,kc,ne=w(()=>{"use strict";Ue={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Ws={COMPLETED:"completed"},Ac={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},de={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Ye={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ht={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},xc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Cc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},At={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},O={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Vs={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"},To={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Pc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},kc={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"}});function Gs(s,e){var t,r,n;return(t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function uw(){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 Hs,qd,Xe,pw,dw,mw,fw,gw,_c,Oc,zd=w(()=>{"use strict";ne();Hs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},qd=s=>Boolean(s.resultId&&s.source==="remote-run"),Xe=(s,e)=>s.testStatus===Ye.QUARANTINE&&!qd(e)&&!e.runQuarantinedTests;pw=s=>Boolean(s.loginMode),dw=s=>Boolean(s.tunnelOnlyMode),mw=s=>Boolean(s.createPrefechedData),fw=s=>Boolean(s.installLazyDepsMode),gw=s=>Boolean(s.agentMode),_c=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Oc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function vo(s=0){return wo.default.duration(s).format("HH:mm:ss.SSS")}function Lc(s=0){return wo.default.duration(s).asSeconds()}var wo,Kd,Jd=w(()=>{"use strict";wo=S(require("dayjs")),Kd=S(require("dayjs/plugin/duration"));wo.default.extend(Kd.default)});var qs,Gr,zs,Yd,Hr,Xd=w(()=>{"use strict";ne();qs=s=>!(!s||"fileName"in s),Gr=(s,e)=>{if(e===O.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},zs=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Yd=s=>s===O.TESTIM_TVC,Hr=(s,e)=>Yd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Dc(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 Qd=w(()=>{"use strict"});var Y={};G(Y,{OSS:()=>qr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>Ka,calcPercentile:()=>Io,copyDir:()=>Gd,delay:()=>ae,doesPathExist:()=>ge,download:()=>Nt,downloadAndSave:()=>Je,extractElementId:()=>Le,getArgsOnRemoteRunFailure:()=>uw,getBrowserInfo:()=>yw,getCdpAddressForHost:()=>yr,getCliLocation:()=>gt,getDuration:()=>vo,getDurationSec:()=>Lc,getEnginesVersion:()=>lw,getEnvironmentGitBranch:()=>hr,getLinksFromUnescapeHTML:()=>Ys,getLocalFileSizeInMB:()=>Rc,getMemorySnapshot:()=>Dc,getPlanType:()=>Eo,getRunConfigByBrowserName:()=>Ks,getRunnerVersion:()=>ft,getSource:()=>bo,getSourceAsBuffer:()=>Ic,getSourcePath:()=>yo,getTestUrl:()=>qe,getUniqBrowsers:()=>Gs,groupTestsByRetries:()=>Nc,guid:()=>se,hasTestPlanFlag:()=>Hs,isAgentMode:()=>gw,isAppFromDevice:()=>qs,isAppFromDeviceDisabled:()=>Hr,isCreatePrefetchedDataMode:()=>mw,isInstallLazyDepsMode:()=>fw,isLoginMode:()=>pw,isMobileProject:()=>zs,isPromise:()=>mc,isQuarantineAndNotRemoteRun:()=>Xe,isRemoteRun:()=>qd,isTestimVirtualGrid:()=>Yd,isTunnelOnlyMode:()=>dw,isURL:()=>ke,promiseAbort:()=>fc,promiseFromCallback:()=>Xt,promiseMap:()=>ie,promiseTimeout:()=>ce,removePropertyFromObject:()=>So,replaceArgsWithNoDashes:()=>_c,shouldBlockVirtualIosBuild:()=>Gr,spreadObjectToArgs:()=>Oc,unescapeHTML:()=>Js,unzipFile:()=>nt});function yw(s){return s=s.toLowerCase(),Mc.find(e=>e.browserValue===s)}function Ks(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Mc.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||Mc[0],n=qr.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=qr.find(o=>o.sl.platform===e.platform):e.platformName&&(n=qr.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=qr.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=qr.find(o=>o.bs.platform===t.platform))),zr.merge(r,n)}function hr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function So(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&So(s[r],e,t))}function Le(s){return s.ELEMENT||s[Kt]}function Eo(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Nc(s=[]){return zr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((o,i)=>{let a=typeof o.retryCount=="number"?o.retryCount:1,l=typeof i.retryCount=="number"?i.retryCount:1;return a===l?o.startTime-i.startTime:(o.retryCount??0)-(i.retryCount??0)}),n=zr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Js(s){return rm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Ys(s){return[...rm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function yr(s,e){let t=await Promise.resolve().then(()=>(Ge(),Ke));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var Zd,zr,em,tm,hw,Ft,qr,Mc,Io,rm,B=w(()=>{"use strict";Zd=S(require("os")),zr=S(require("lodash")),em=S(require("path")),tm=require("linkedom");Ur();Hd();zd();Jd();Ja();gc();Xd();Qd();hw=Zd.homedir(),Ft=em.join(hw,".testim-browser-profile"),qr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Mc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Io=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};rm=new tm.DOMParser});var Uc={};G(Uc,{$schema:()=>bw,default:()=>Ew,definitions:()=>Tw,properties:()=>Sw,required:()=>vw,type:()=>ww});var bw,Tw,ww,vw,Sw,Ew,sm=w(()=>{bw="http://json-schema.org/draft-07/schema#",Tw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},ww="object",vw=["entries"],Sw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Ew={$schema:bw,definitions:Tw,type:ww,required:vw,properties:Sw}});async function um(){try{return await ce(Ro.promises.readFile(Po()).then(async s=>{let e=await lm;return Aw(e,s)}),3e4)}catch{return{}}}function Aw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=Jr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(r);return JSON.parse(Buffer.concat([i,o.final()]))}function yt(s,e,t=Iw,r=void 0){return async()=>{if(!im)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await xw(e);if(o)return Xs.debug("cache hit:",{fnName:e}),o;if(Xs.debug("cache miss:",{fnName:e}),!am)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await s();return i&&await Cw(e,i,t),i}}async function xw(s){let t=(await ko)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Cw(s,e,t){if(Fc)throw Xs.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 ko;r[s]={value:e,expiry:Date.now()+t},cm=new Promise(n=>{Co=n}),Rw(r)}catch{Xs.error("failed updating cache")}}async function Yr(){let s=await ko;Object.keys(s).forEach(e=>{delete s[e]})}function pm(s){im=s}function Pw(s=!0){am=s}async function dm(){try{return Fc=!0,await cm}finally{Fc=!1}}function mm(s){xo=s,ko=um()}var Ro,Ao,Jr,nm,Xs,xo,om,Co,im,am,Fc,cm,lm,Iw,Po,ko,Rw,fm,gm,rA,hm,Bt=w(()=>{"use strict";Ro=S(require("fs")),Ao=S(require("path")),Jr=S(require("crypto"));B();nm=require("lodash");$();Xs=C("local cache"),xo=Ao.resolve(gt(),"testim-cache"),im=!0,am=!0,Fc=!1,cm=new Promise(s=>{Co=s}),lm=new Promise(s=>{om=s}),Iw=1e3*60*60*3,Po=()=>Ao.resolve(Ao.resolve(xo,"testim.cache"));ko=um(),Rw=(0,nm.debounce)(async s=>{let e;try{let t=await lm,r=Jr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=Jr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await ge(xo)||await Ro.promises.mkdir(xo,{recursive:!0}),await Ro.promises.writeFile(Po(),a)}catch(t){Xs.error("failed saving cache",{err:t}),e=t}Co(e?{success:!1,error:e}:{success:!0})},200);fm=om,gm=pm.bind(void 0,!1),rA=pm.bind(void 0,!0),hm=()=>Pw(!1)});function _o(){return{cliLocation:gt(),userInfo:Xr.userInfo(),platform:Xr.platform(),release:Xr.release()}}var Xr,Bc=w(()=>{"use strict";Xr=S(require("os"));B()});function kw(s){try{return Oo.resolve(Oo.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 Zt(s){let e=kw(s);return require(e)}var Oo,Qs=w(()=>{"use strict";Oo=S(require("path"))});function _w(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Ow(s){return/The "to" argument must be of type string./.exec(s)}function wm(s,e,t){let r=_w(s),n=Ow(s);return r||n?(Tm.info("Failed to install package due to insufficient write access",{..._o(),package:t,path:r}),console.error(`
|
|
2
|
+
"use strict";var kT=Object.create;var Qn=Object.defineProperty;var _T=Object.getOwnPropertyDescriptor;var OT=Object.getOwnPropertyNames;var LT=Object.getPrototypeOf,DT=Object.prototype.hasOwnProperty;var w=(s,e)=>()=>(s&&(e=s(s=0)),e);var H=(s,e)=>{for(var t in e)Qn(s,t,{get:e[t],enumerable:!0})},rd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of OT(e))!DT.call(s,n)&&n!==t&&Qn(s,n,{get:()=>e[n],enumerable:!(r=_T(e,n))||r.enumerable});return s};var S=(s,e,t)=>(t=s!=null?kT(LT(s)):{},rd(e||!s||!s.__esModule?Qn(t,"default",{value:s,enumerable:!0}):t,s)),Ne=s=>rd(Qn({},"__esModule",{value:!0}),s);var je={};H(je,{log:()=>N,measure:()=>NT});function N(...s){if(!nd)return;let e=Date.now();console.log(`${e-MT} ${e-sd} `,...s),sd=e}function NT(s,e){if(!nd)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var nd,MT,sd,$e=w(()=>{"use strict";nd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,MT=Date.now(),sd=Date.now()});var Kt,Ur=w(()=>{"use strict";Kt="element-6066-11e4-a52e-4f735466cecf"});function se(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function qe(s,e,t,r,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(o+=`?result-id=${r}`)),o}function Ka(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function ke(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 Ja=w(()=>{"use strict"});var Xa,od,id,io=w(()=>{Xa={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},od={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"1.3.0","@types/unzip-stream":"0.3.2",ajv:"6.12.6","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4","coralogix-logger":"1.1.28",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",express:"4.19.2",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.22.10",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"4.9.18",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.6.2","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"6.0.0","ua-parser-js":"0.7.33","unzip-stream":"0.3.1","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},id={node:">= 18.0.0"}});var Os,BT,ad,cd,ld,ao,Ls,ud,fe,pd,dd,co,_e,Qa,md,lo,fd,xR,CR,gd,hd,Fr,yd,bd,Td,wd,vd,Za,ec,tc,rc,Sd,Ds,Ed,Id,Rd,sc,pe=w(()=>{"use strict";Os=process.env.SERVICES_HOST||"https://services.testim.io",BT="https://testimstatic.blob.core.windows.net",ad="https://tstresultfiles.azureedge.net";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:Os,Os=process.env.SERVICES_HOST);cd=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),ld=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),ao=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Ls=process.env.EDITOR_URL,ud=process.env.WEBSOCKET_HOST||`${Os}/ws`,fe=Os,pd=parseInt(process.env.LOGGER_CONSOLE||"0",10),dd=parseInt(process.env.LOGGER_DEBUG||"0",10),co=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),_e=parseInt(process.env.IS_ON_PREM||"0",10),Qa=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,md=parseInt(process.env.DEBUG_MODE||"0",10),lo=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,fd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",xR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),CR=process.env.APPIUM_VERSION||"1.10.1",gd=process.env.GATEWAY_URL,hd=process.env.EXTENSION_SERVICES_HOST||Os,Fr=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:BT,yd=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:ad,bd=ad,Td=5*60*1e3,wd=40,vd=process.env.TMA_BASE_API_URL||"http://127.0.0.1:8585/api",Za=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",ec=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",tc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",rc=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Sd=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Ds=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Ed=process.env.SAUCE_LABS_US_APPS_API_URL||"https://api.us-west-1.saucelabs.com/v1",Id=process.env.SAUCE_LABS_EU_APPS_API_URL||"https://api.eu-central-1.saucelabs.com/v1",Rd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,sc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var nc={};H(nc,{CoralogixTransport:()=>Br});var Ie,Ad,jT,$T,Br,oc=w(()=>{"use strict";Ie=require("coralogix-logger"),Ad=S(require("winston-transport")),jT={debug:Ie.Severity.debug,silly:Ie.Severity.verbose,verbose:Ie.Severity.verbose,silent:Ie.Severity.verbose,info:Ie.Severity.info,http:Ie.Severity.info,warn:Ie.Severity.warning,warning:Ie.Severity.warning,error:Ie.Severity.error,critical:Ie.Severity.critical,crit:Ie.Severity.critical},$T=["err","error","reason","e"],Br=class extends Ad.default{constructor(t){t={...Br.options,...t};super(t);this.options=t,this.logger=new Ie.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,r){let{category:n,level:o,message:i,meta:a={},...l}=t,c={...a,...this.options.extraFields,...l},d=new Ie.Log;d.severity=jT[o],d.text=i,d.category=n,c.className&&(d.className=c.className),c.methodName&&(d.methodName=c.methodName),c.threadId&&(d.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let m=!1;a instanceof Error&&(m=!0,c.msg=a.message+a.stack,i&&(c.msg=`${i}
|
|
3
|
+
${c.msg}`));for(let u of $T)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(i&&!m&&(c.msg=i),d.text=c),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Ie.CoralogixLogger.configure(t),Br.options=t}}});var dc={};H(dc,{getLogger:()=>C,sessionPlayerLoggerFormatter:()=>cc,setExecutionId:()=>lc,setProjectId:()=>uc,setProxyUri:()=>pc});function GT(){let s=[],e=()=>Promise.resolve();if(!_e){let{CoralogixTransport:t}=(oc(),Ne(nc));t.configure(_d);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}if(pd){let t={depth:5,colors:!0};s.push(new dt.transports.Console({format:dt.format.combine(dt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),dt.format.timestamp({format:"HH:mm:ss:SSS"}),dt.format.printf(r=>`[${r.timestamp}] ${r.level} ${r.category}: ${r.message} ${po.inspect(r.meta,t)}`))}))}return[s,e]}function lc(s){ic=s}function uc(s){Od=s}function pc(s){if(_e||!s)return;let{CoralogixTransport:e}=(oc(),Ne(nc));e.configure({..._d,proxyUri:s})}function Cd(s){return{projectId:Od,time:new Date().toISOString(),...ic&&!s&&{executionId:ic}}}function C(s){return new ac(JT.child({category:s}))}var Pd,dt,po,uo,kd,WT,VT,_d,xd,cc,HT,qT,zT,KT,JT,ic,Od,ac,$=w(()=>{"use strict";Pd=S(require("os")),dt=S(require("winston"));pe();po=S(require("util")),uo=S(require("chalk")),kd=S(require("dayjs"));B();WT=Pd.hostname(),VT=mt(),_d={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};xd={depth:5,colors:!0},cc=(s,e,t)=>{let r=`[${(0,kd.default)().format("HH:mm:ss:SSS")}]`,n=po.inspect(e,xd),o=po.inspect(t,xd);return`${uo.default.white(r)} ${uo.default.reset()}SessionPlayer-${uo.default.red(s)} ${n} ${o}`},[HT,qT]=GT(),zT=dd?"debug":"info",KT={release:Boolean(!0),branch:"production"},JT=dt.createLogger({levels:dt.config.syslog.levels,level:zT,transports:HT,defaultMeta:{name:"runner",hostname:WT,nodeVersion:process.version,runnerVersion:VT,...KT}}),ic=null,Od=null;ac=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Cd(n)})}catch(o){try{this._logger.log("crit",{message:`failed to log message ${o.message}, ${o.stack}`,...Cd(n)})}catch{}}}waitForFlush(){return qT()}}});var ho,jr,P,Jt,mr,Et,mo,$r,oe,Ms,ze,Yt,It,fo,Wr,go,Ns,K=w(()=>{"use strict";ho=require("p-retry"),jr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},P=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Jt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},mr=class extends Error{constructor(t,r){super(t);this.type=r}},Et=class extends ho.AbortError{},mo=class extends ho.AbortError{},$r=class extends ho.AbortError{},oe=class extends Error{},Ms=class extends Error{},ze=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Yt=class extends ze{constructor(){super(...arguments);this.name="GridConcurrencyError"}},It=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},fo=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Wr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},go=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Ns=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function mc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ae(s){return(0,Md.setTimeout)(s)}function fc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function ce(s,e,t="Timeout Error"){ao&&!Ld&&(Ld=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new oe(t);return e=ao?Number(ao)||6e5:e,Promise.race([s,ae(e).then(()=>{throw r})])}async function ie(s,e,{concurrency:t}={}){if(t){Dd||=(await import("p-limit")).default;let r=Dd(t);return await Promise.all(Array.from(s,(n,o)=>r(()=>e(n,o))))}return await Promise.all(Array.from(s,e))}function Xt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Md,Ld,Dd,gc=w(()=>{"use strict";Md=require("timers/promises");K();pe();Ld=!1});var Fs,Nd,YT,Us,Ud,XT,QT,Fd,Bd=w(()=>{"use strict";Fs=S(require("lodash"));pe();Nd=require("dns");$();gc();YT=C("http-request-counters"),Us=!1,Ud=async()=>{if(_e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ie(s,t=>Nd.promises.lookup(t)));return e||(Us=!0),e}catch{return YT.error("network connectivity test failed"),Us=!0,!1}},XT=Fs.throttle(Ud,10*1e3),QT=60*1e3*15,Fd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},QT)}function t(n,o=n.name){return async function(...i){e(s.call,o);try{let a=await n.call(null,...i);return e(s.success,o),a}catch(a){throw e(s.fail,o),Us||XT(),a}}}async function r(){if(Us||!await Ud())return!1;let n=Fs.sum([...s.fail.values()]),o=Fs.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Us,t}});var Ke={};H(Ke,{deleteFullRes:()=>sw,deleteReq:()=>Bs,didNetworkConnectivityTestFail:()=>Ec,download:()=>vc,get:()=>be,getFullRes:()=>ow,getText:()=>$s,head:()=>iw,isNetworkHealthy:()=>Sc,post:()=>Ve,postForm:()=>js,postFullRes:()=>nw,postText:()=>Tc,put:()=>wc});function ew(){return global.caFileContent}function tw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function rw(){return!Rt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(Rt.default),global.proxyUri}function fr(s,e=!1){let t=ew();t&&s.ca(t);let r=!e&&rw();r&&s.proxy(r)}async function jd(s,e={},t={},r=Vr){let n=Rt.default.delete(s).send(e).timeout(r).set(t);return fr(n),await n}async function yc(s,e,t={},r=Vr,n=0){let o=Rt.default.post(s).send(e).timeout(r).set(t);fr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=s,i.originalRequestTimeout=r,i.additionalSetHeaders=t,i}}async function bc(s,e,t={},r=Vr,{isBinary:n=!1,skipProxy:o=!1}={}){let i=Rt.default.get(s).query(e||{}).timeout(r).set(t);return n&&i.buffer(!0),fr(i,o),await i}var Rt,hc,We,Vr,ZT,Dt,Bs,sw,Ve,nw,js,$s,Tc,be,ow,iw,wc,vc,Sc,Ec,Ge=w(()=>{"use strict";Rt=S(require("superagent"));$();Bd();hc=C("http-request"),We=Fd(),Vr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,ZT=6e4;Dt=(s,e,t)=>{throw hc.error(s,{...t,error:e}),e};Bs=We(async(s,e,t,r)=>{try{let n=await jd(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Dt("failed to delete request",n,{url:s})}});sw=We(jd),Ve=We(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await yc(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});nw=We(yc),js=We(async(s,e,t,r={},n=Vr)=>{let o=Rt.default.post(s).type("form").timeout(n).set(r);o.field(e),Object.entries(t).forEach(([i,a])=>{o.attach(i,a.buffer,a.fileName)}),fr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});$s=We(async(s,e,t)=>{try{return(await bc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),Tc=We(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await yc(s,e,t,r,n)).text}catch(o){return Dt("failed to post request",o,{url:s})}}),be=We(async(s,e,t,r,n)=>{try{return(await bc(s,e,t,r,n)).body}catch(o){return Dt("failed to get request",o,{url:s,query:e})}}),ow=We((s,e,t,r)=>bc(s,e,t,r)),iw=We(async s=>{let e=Rt.default.head(s).timeout(Vr);fr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),wc=We(async(s,e,t={},r=Vr)=>{let n=Rt.default.put(s).send(e).timeout(r).set(t);fr(n);try{return(await n).body}catch(o){return Dt("failed to put request",o,{url:s})}}),vc=We(async s=>{hc.info("start to download",{url:s});let e=Rt.default.get(s).timeout(ZT).buffer(!0).parse(tw);fr(e);try{let t=await e;return hc.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),Sc=We.isNetworkHealthy,Ec=We.didNetworkConnectivityTestFail});function ft(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Mt.resolve(__dirname,"../../"):s=Mt.resolve(__dirname,""),s):process.cwd()}function yo(s,e){return ke(s)?e||Mt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Mt.basename(s)}function mt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function cw(){try{return id.node}catch{return""}}async function Vd(s,e,t=!0){let r=await st.promises.readdir(s,{withFileTypes:!0});await st.promises.mkdir(e,{recursive:t});for(let n of r){let o=Mt.join(s,n.name),i=Mt.join(e,n.name);n.isDirectory()?await Vd(o,i):await st.promises.copyFile(o,i)}}async function ge(s){try{return await st.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Mt,$d,Wd,st,aw,Nt,Je,bo,Ic,nt,Rc,Gd=w(()=>{"use strict";Mt=S(require("path"));Ja();io();$d=S(require("unzip-stream")),Wd=S(require("p-retry")),st=require("fs"),aw=3;Nt=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Ke));return(0,Wd.default)(()=>e.download(s),{retries:aw,factor:1})},Je=async(s,e)=>{let t=await Nt(s);return st.promises.writeFile(e,t.body)};bo=async(s,e)=>{let t=yo(s,e);return ke(s)?Je(s,t):st.promises.copyFile(s,t)},Ic=async s=>ke(s)?Nt(s):st.promises.readFile(s),nt=async(s,e)=>await(0,st.createReadStream)(s).pipe($d.Extract({path:e})),Rc=s=>(0,st.statSync)(s).size/1e6});var Ut={};H(Ut,{APPIUM_SESSION_MESSAGE:()=>kc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>To,MOBILE_RUN_SKIP_REASON:()=>Pc,gridMessages:()=>gt,gridTypes:()=>O,mobileWeb:()=>xc,runnerStatus:()=>Ac,runnerTestStatus:()=>de,socketEventTypes:()=>At,stepResult:()=>Vs,test:()=>Cc,testRunStatus:()=>Ws,testStatus:()=>Ye,timeoutMessages:()=>Ue});var Ue,Ws,Ac,de,Ye,gt,xc,Cc,At,q,O,Vs,To,Pc,kc,ne=w(()=>{"use strict";Ue={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Ws={COMPLETED:"completed"},Ac={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},de={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Ye={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},gt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},xc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Cc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},At={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},O={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Vs={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"},To={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Pc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},kc={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"}});function Gs(s,e){var t,r,n;return(t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function lw(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var Hs,Hd,Xe,uw,pw,dw,mw,fw,_c,Oc,qd=w(()=>{"use strict";ne();Hs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},Hd=s=>Boolean(s.resultId&&s.source==="remote-run"),Xe=(s,e)=>s.testStatus===Ye.QUARANTINE&&!Hd(e)&&!e.runQuarantinedTests;uw=s=>Boolean(s.loginMode),pw=s=>Boolean(s.tunnelOnlyMode),dw=s=>Boolean(s.createPrefechedData),mw=s=>Boolean(s.installLazyDepsMode),fw=s=>Boolean(s.agentMode),_c=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Oc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function vo(s=0){return wo.default.duration(s).format("HH:mm:ss.SSS")}function Lc(s=0){return wo.default.duration(s).asSeconds()}var wo,zd,Kd=w(()=>{"use strict";wo=S(require("dayjs")),zd=S(require("dayjs/plugin/duration"));wo.default.extend(zd.default)});var qs,Gr,zs,Jd,Hr,Yd=w(()=>{"use strict";ne();qs=s=>!(!s||"fileName"in s),Gr=(s,e)=>{if(e===O.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},zs=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Jd=s=>s===O.TESTIM_TVC,Hr=(s,e)=>Jd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Dc(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 Xd=w(()=>{"use strict"});var J={};H(J,{OSS:()=>qr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>Ka,calcPercentile:()=>Io,copyDir:()=>Vd,delay:()=>ae,doesPathExist:()=>ge,download:()=>Nt,downloadAndSave:()=>Je,extractElementId:()=>Le,getArgsOnRemoteRunFailure:()=>lw,getBrowserInfo:()=>hw,getCdpAddressForHost:()=>hr,getCliLocation:()=>ft,getDuration:()=>vo,getDurationSec:()=>Lc,getEnginesVersion:()=>cw,getEnvironmentGitBranch:()=>gr,getLinksFromUnescapeHTML:()=>Ys,getLocalFileSizeInMB:()=>Rc,getMemorySnapshot:()=>Dc,getPlanType:()=>Eo,getRunConfigByBrowserName:()=>Ks,getRunnerVersion:()=>mt,getSource:()=>bo,getSourceAsBuffer:()=>Ic,getSourcePath:()=>yo,getTestUrl:()=>qe,getUniqBrowsers:()=>Gs,groupTestsByRetries:()=>Nc,guid:()=>se,hasTestPlanFlag:()=>Hs,isAgentMode:()=>fw,isAppFromDevice:()=>qs,isAppFromDeviceDisabled:()=>Hr,isCreatePrefetchedDataMode:()=>dw,isInstallLazyDepsMode:()=>mw,isLoginMode:()=>uw,isMobileProject:()=>zs,isPromise:()=>mc,isQuarantineAndNotRemoteRun:()=>Xe,isRemoteRun:()=>Hd,isTestimVirtualGrid:()=>Jd,isTunnelOnlyMode:()=>pw,isURL:()=>ke,promiseAbort:()=>fc,promiseFromCallback:()=>Xt,promiseMap:()=>ie,promiseTimeout:()=>ce,removePropertyFromObject:()=>So,replaceArgsWithNoDashes:()=>_c,shouldBlockVirtualIosBuild:()=>Gr,spreadObjectToArgs:()=>Oc,unescapeHTML:()=>Js,unzipFile:()=>nt});function hw(s){return s=s.toLowerCase(),Mc.find(e=>e.browserValue===s)}function Ks(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Mc.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||Mc[0],n=qr.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=qr.find(o=>o.sl.platform===e.platform):e.platformName&&(n=qr.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=qr.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=qr.find(o=>o.bs.platform===t.platform))),zr.merge(r,n)}function gr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function So(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&So(s[r],e,t))}function Le(s){return s.ELEMENT||s[Kt]}function Eo(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Nc(s=[]){return zr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((o,i)=>{let a=typeof o.retryCount=="number"?o.retryCount:1,l=typeof i.retryCount=="number"?i.retryCount:1;return a===l?o.startTime-i.startTime:(o.retryCount??0)-(i.retryCount??0)}),n=zr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Js(s){return tm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Ys(s){return[...tm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function hr(s,e){let t=await Promise.resolve().then(()=>(Ge(),Ke));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var Qd,zr,Zd,em,gw,Ft,qr,Mc,Io,tm,B=w(()=>{"use strict";Qd=S(require("os")),zr=S(require("lodash")),Zd=S(require("path")),em=require("linkedom");Ur();Gd();qd();Kd();Ja();gc();Yd();Xd();gw=Qd.homedir(),Ft=Zd.join(gw,".testim-browser-profile"),qr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Mc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Io=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};tm=new em.DOMParser});var Uc={};H(Uc,{$schema:()=>yw,default:()=>Sw,definitions:()=>bw,properties:()=>vw,required:()=>ww,type:()=>Tw});var yw,bw,Tw,ww,vw,Sw,rm=w(()=>{yw="http://json-schema.org/draft-07/schema#",bw={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}}}},Tw="object",ww=["entries"],vw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Sw={$schema:yw,definitions:bw,type:Tw,required:ww,properties:vw}});async function lm(){try{return await ce(Ro.promises.readFile(Po()).then(async s=>{let e=await cm;return Rw(e,s)}),3e4)}catch{return{}}}function Rw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=Jr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(r);return JSON.parse(Buffer.concat([i,o.final()]))}function ht(s,e,t=Ew,r=void 0){return async()=>{if(!om)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await Aw(e);if(o)return Xs.debug("cache hit:",{fnName:e}),o;if(Xs.debug("cache miss:",{fnName:e}),!im)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await s();return i&&await xw(e,i,t),i}}async function Aw(s){let t=(await ko)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function xw(s,e,t){if(Fc)throw Xs.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 ko;r[s]={value:e,expiry:Date.now()+t},am=new Promise(n=>{Co=n}),Iw(r)}catch{Xs.error("failed updating cache")}}async function Yr(){let s=await ko;Object.keys(s).forEach(e=>{delete s[e]})}function um(s){om=s}function Cw(s=!0){im=s}async function pm(){try{return Fc=!0,await am}finally{Fc=!1}}function dm(s){xo=s,ko=lm()}var Ro,Ao,Jr,sm,Xs,xo,nm,Co,om,im,Fc,am,cm,Ew,Po,ko,Iw,mm,fm,tA,gm,Bt=w(()=>{"use strict";Ro=S(require("fs")),Ao=S(require("path")),Jr=S(require("crypto"));B();sm=require("lodash");$();Xs=C("local cache"),xo=Ao.resolve(ft(),"testim-cache"),om=!0,im=!0,Fc=!1,am=new Promise(s=>{Co=s}),cm=new Promise(s=>{nm=s}),Ew=1e3*60*60*3,Po=()=>Ao.resolve(Ao.resolve(xo,"testim.cache"));ko=lm(),Iw=(0,sm.debounce)(async s=>{let e;try{let t=await cm,r=Jr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=Jr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await ge(xo)||await Ro.promises.mkdir(xo,{recursive:!0}),await Ro.promises.writeFile(Po(),a)}catch(t){Xs.error("failed saving cache",{err:t}),e=t}Co(e?{success:!1,error:e}:{success:!0})},200);mm=nm,fm=um.bind(void 0,!1),tA=um.bind(void 0,!0),gm=()=>Cw(!1)});function _o(){return{cliLocation:ft(),userInfo:Xr.userInfo(),platform:Xr.platform(),release:Xr.release()}}var Xr,Bc=w(()=>{"use strict";Xr=S(require("os"));B()});function Pw(s){try{return Oo.resolve(Oo.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 Zt(s){let e=Pw(s);return require(e)}var Oo,Qs=w(()=>{"use strict";Oo=S(require("path"))});function kw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function _w(s){return/The "to" argument must be of type string./.exec(s)}function Tm(s,e,t){let r=kw(s),n=_w(s);return r||n?(bm.info("Failed to install package due to insufficient write access",{..._o(),package:t,path:r}),console.error(`
|
|
4
4
|
|
|
5
5
|
Testim failed installing the package ${t||""} due to insufficient permissions.
|
|
6
6
|
This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
|
|
7
7
|
Testim had missing write access to ${r||e}
|
|
8
8
|
|
|
9
|
-
`),!0):!1}async function
|
|
10
|
-
stdout: ${l} stderr: ${c}`}
|
|
9
|
+
`),!0):!1}async function wm(s){return(await ym(`npm view ${s} version`)).stdout.trim()}function Wc(s){try{return Zt(s)}catch{return!1}}function vm(s,e){return require(yr.join(s,`./node_modules/${e}/package.json`)).version}function Sm(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=Sm(s[e]);if(t)return t}}function Em(s){let e=require(yr.join(s,"package.json"));if(!("exports"in e))return"";let t=Sm(e);if(!t)throw new go(e.name);return t}async function Do(s,e,t){let r=yr.join(s,"npm-shrinkwrap.json"),n=yr.join(s,"npm-shrinkwrap-dummy.json"),o=!1;try{try{await ge(r)&&(await $c.promises.rename(r,n),o=!0)}catch{}return await ym(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(i=>{throw Tm(i.stderr,s,e)?new Wr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):i})}finally{if(o)try{await $c.promises.rename(n,r)}catch{}}}function Im(s,e,t,r){return new Promise((n,o)=>{let i=t?["--proxy",t]:[],a=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},l="",c="",d="--no-save --no-package-lock --no-prune --prefer-offline --no-audit --progress=false".split(" "),m=(0,Lo.spawn)("node",[jc,"i","--prefix",s,...d,...e,...i],a);m.stderr.pipe(process.stderr),m.stdout.pipe(process.stdout),m.stdout.on("data",u=>{l+=u}),m.stderr.on("data",u=>{c+=u}),m.on("close",u=>{var f,h;if(u){let g;try{let y=(f=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(c))==null?void 0:f[1],T=(h=/No matching version found for (\S+)@/gm.exec(c))==null?void 0:h[1];y||T?g=`404 Not Found - GET https://registry.npmjs.org/${T??y} - Not found`:Tm(c,jc)?g=`insufficient write access in location ${jc}`:g=`Npm Installation closed with exit code ${u} with error: ${c}`}catch{g=`Npm Install closed with exit code ${u}
|
|
10
|
+
stdout: ${l} stderr: ${c}`}bm.info(`Npm Install closed with exit code ${u}`,{message:g,stderr:c}),o(new It(g))}else n(l)}),setTimeout(()=>{try{m.kill()}finally{o(new oe)}},r)})}var $c,yr,hm,Lo,ym,bm,jc,Qr=w(()=>{"use strict";$c=S(require("fs")),yr=S(require("path"));B();hm=require("util"),Lo=require("child_process");$();Bc();Qs();K();ym=(0,hm.promisify)(Lo.exec),bm=C("cli-service");jc=yr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var W,Am,Ow,Lw,Dw,Rm,No,Vc,D,le=w(()=>{"use strict";W=S(require("rox-node"));$();B();pe();Am=C("FeatureFlagsService"),Ow=!_e&&!0&&!gd,Lw=2e4,Dw=60*60*24,Rm=["labs","disabled","enabled"],No=class extends W.default.Variant{constructor(e="disabled"){super(e,Rm)}getValue(){let e=super.getValue();return Rm.includes(e)?e:(Am.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Vc=class{constructor(){this.flags={useNewWSCLI:new W.default.Flag,useSafariWebdriverVisibilityChecks:new W.default.Flag,useClickimVisibilityChecks:new W.default.Flag,runGetElementCodeInAut:new W.default.Flag,enableFrameSwitchOptimization:new W.default.Flag,maximumJsResultSize:new W.default.Configuration(2e3*1024),skipFileInputClicks:new W.default.Flag,errorMessageOnBadNetwork:new W.default.Flag(!0),warnOnBadNetwork:new W.default.Flag(!1),overrideAzureStorageUrl:new W.default.Flag,autoSaveDownloadFileFireFox:new W.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new W.default.Flag(!0),experimentalPreCodeCompilation:new W.default.Flag(!0),experimentalAsyncCustomCode:new W.default.Flag,useSameBrowserForMultiTests:new No("labs"),highSpeedMode:new No,usePortedHtml5DragDrop:new W.default.Flag,testNamesToBeforeSuiteHook:new W.default.Flag,addCustomCapabilities:new W.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new W.default.Variant("{}"),LTNetworkCapabilities:new W.default.Flag,downloadToBase64:new W.default.Flag,publicGridURL:new W.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new W.default.Flag(!0),unsupportedCapsFields:new W.default.Variant("[]"),dontFocusOnInit:new W.default.Flag,retryOnSeleniumHubError:new W.default.Flag,enableLambdaTestTunnelNTLM:new W.default.Flag,enableLambdaTestTunnelSkipUpgrade:new W.default.Flag,tdcHsPreventNetworkCapture:new W.default.Flag,headSpinTdcEnableFlagCapability:new W.default.Flag,enableBatchTDC:new W.default.Flag,enableBatchHeadSpin:new W.default.Flag,clearRunnerFileCache:new W.default.Flag,forceTurboModeIfNeeded:new W.default.Flag,redisSlotManager:new W.default.Flag,tunnelBinaryNewVersion:new W.default.Flag(!1),encryptedCredentials:new W.default.Flag,computePackagePathFromPackageJsonExports:new W.default.Flag,sendExtensionOnEdgeNonLinux:new W.default.Flag,enableAppium2pCloudy:new W.default.Flag,reuseCliPkgInstallFolder:new W.default.Flag,getPublicIpFrom3rdPartyServices:new W.default.Flag,chromedriverCdnBinariesUrl:new W.default.Variant(""),sfdcHybridCompany:new W.default.Flag,allowFixingAppIdStructure:new W.default.Flag,enableAppium2BrowserStack:new W.default.Flag,increaseTDCRequestTimeout:new W.default.Flag,accessTokenExpiryMargin:new W.default.Configuration(300*1e3),useMV3Extension:new W.default.Flag},W.default.register("default",this.flags)}setProjectId(e){W.default.setCustomStringProperty("projectId",e)}setProjectType(e){W.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){W.default.setCustomStringProperty("productType",e)}setCompanyId(e){W.default.setCustomStringProperty("companyId",e)}setPlanType(e){W.default.setCustomStringProperty("planType",e)}setIsPOC(e){W.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){W.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){W.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Ow)return;let e={fetchIntervalInSec:Dw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ce(W.default.setup(fd,e),Lw).catch(t=>Am.error("failed to get feature flag status",t))}},D=new Vc});var _m={};H(_m,{install:()=>Nw,isReady:()=>Fw,start:()=>Uw});var xm,Cm,Pm,km,Gc,Mw,Nw,Uw,Fw,Om=w(()=>{"use strict";xm=S(require("fkill")),Cm=S(require("p-retry"));Qr();Ge();B();Qs();le();Pm="chromedriver",km=9515,Gc=`http://localhost:${km}/wd/hub`,Mw=["--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],Nw=async()=>{let s=D.flags.chromedriverCdnBinariesUrl.getValue(),e=ke(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await Do(ft(),`${Pm} --detect_chromedriver_version ${e}`)},Uw=async()=>{process.env.NODE_OPTIONS="",await(0,xm.default)(`:${km}`,{silent:!0}),await Zt(Pm).start(Mw,!0)},Fw=async({chromeBinaryLocation:s})=>{await(0,Cm.default)(async()=>{var n;let e=await be(`${Gc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Ve({url:`${Gc}/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 Bs(`${Gc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var en={};H(en,{getSessionPlayerFolder:()=>Kc,prepareChromeDriver:()=>Zs,prepareCustomExtension:()=>qc,prepareExtension:()=>zc,preparePlayer:()=>br});async function qc(s,e=!1){if(!s)return;if(ke(s)){let n=Zr.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Bw(s)>Hc&&!e)throw new P(Lm);return await Je(s,n),n}let t=Zr.resolve(s);if(!Mm.existsSync(t))throw new P(`Failed to find custom extension in location: ${t}`);if(Rc(t)>Hc&&!e)throw new P(Lm);return t}async function Bw(s){let e=(Ge(),Ne(Ke));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Uo.warn("failed to download custom extension",{err:t}),new P(`Failed to download custom extension from location: ${s}`)}}function zc(s){Uo.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:yo(t)}));return ht(()=>ie(e,({location:t,path:r})=>bo(t,r)),"prepareExtension",Um,e)()}async function Zs(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),o=await Promise.resolve().then(()=>(Om(),_m));try{await o.install(),await o.start(),t||await o.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(i){let a="Failed to initiate Chrome Driver";throw i instanceof Wr||(Uo.error(a,{...s,..._o(),error:(0,Nm.serializeError)(i)}),console.log(`
|
|
11
11
|
1. If you don't have Chrome, please install it from https://www.google.com/chrome.
|
|
12
12
|
2. If Chrome is installed, please verify it's binary directory:
|
|
13
13
|
- installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
|
|
14
14
|
- exists in your PATH environment variables.
|
|
15
15
|
3. Try adding --chrome-binary-location flag to Testim CLI specifying the exact location of chrome binary in your computer (e.g on Windows "C:/Program Files/Google/Chrome/Application/chrome.exe").
|
|
16
|
-
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),i}}async function $w(){let s=`${Fr}/extension/sessionPlayer_LATEST_RELEASE`;return(await Nt(s)).body.toString("utf8")}async function Ww(s,e){if(!ke(s)||ke(s)&&e||_e)return s;let t=await $w();return`${s}-${t}`}function Kc(){let s=gt();return Zr.resolve(s,"testim-bin")}function Vw(){let s=Kc();return Zr.resolve(s,"sessionPlayer.zip")}async function Bm(s,e,t=!1){try{return await bo(s,e),await nt(e,Kc())}catch(r){if(t)throw r;return await Bm(s,e,!0)}}async function Tr(s,e){Uo.info("prepare player",{location:s,canary:e});let t=Vw();return yt(async()=>{let r=await Ww(s,e);return await Bm(r,t),{}},"preparePlayer",Fm,[s,e,t])()}var Mm,Nm,Zr,Um,Uo,Fm,Hc,Dm,tn=w(()=>{"use strict";Mm=S(require("ms")),Nm=S(require("fs")),Zr=S(require("path"));pe();Bt();Um=require("serialize-error");$();Bc();J();B();Uo=C("prepare runner and testim start"),Fm=(0,Mm.default)("0.5 day"),Hc=16,Dm=`The size of the custom extension is more than ${Hc}MB`});function Gw(){let s=rn.type().toLowerCase();return s==="darwin"?rn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?rn.arch()==="x64"?"win64":"win32":"linux"}async function Bo(){let s=Gw(),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 P(`Unsupported platform: ${s}`);let r=parseInt(sn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${sn}/${n[s]}.zip`,a=Fo.join(Jc,n[s]),l=`${a}.zip`,c=Fo.join(a,o[s]);if(await ge(c))return c;if(!await ge(l)){let m=(0,Yc.default)("Downloading Chromium").start();try{await jm.promises.mkdir(Jc),await Je(i,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,Yc.default)("Extracting Chromium").start();try{await nt(l,Jc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var jm,rn,Fo,Yc,sn,Jc,Xc=w(()=>{"use strict";jm=S(require("fs")),rn=S(require("os")),Fo=S(require("path")),Yc=S(require("ora"));J();B();sn="1000968",Jc=Fo.join(Ft,`chrome-${sn}`)});async function Vm(s,e){return wr=s,tl=e,await Qc()}function Gm(s,e){wr=e.projectId,tl=e.token,nn=e.userAccessKey,ot=s.token,an=rl(ot),cn=s.refreshToken,Zc=s.ngrokToken,el=s.isNgrokWhitelisted,$m=e.publicIp,Wm=e.initializedFromCache}function qw(s=wr,e=tl){return yt(()=>(on.info("request to get cli token from server"),Ve({url:`${fe}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Hw*10,{projectId:s,token:e})()}async function zw(){on.info("request to refresh JWT cli token from server");let s=await Ve({url:`${fe}/auth/refreshToken`,body:{token:ot,refreshToken:cn}});return ot=s.token,an=rl(ot),s.refreshToken&&(cn=s.refreshToken),ot}async function Qc(){try{let s=await qw();return on.info("successfully get cli token from server"),ot=s.token,an=rl(ot),cn=s.refreshToken,Zc=s.ngrokToken,el=s.isNgrokWhitelisted,ot}catch(s){throw s.message.includes("Unauthorized")?new P("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."):(on.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:wr}),new P(`While trying to retrieve CLI token, caught error: ${s}`))}}function rl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function xt(){if(!an)return Qc();let s=D.flags.accessTokenExpiryMargin.getValue();if(an<Date.now()+4*s)try{return await zw()}catch(e){return on.error("failed to refresh token, executing fallback",e),Qc()}return ot}function jo(){return cn}function jt(){return ot?{uid:require("jsonwebtoken").decode(ot).id,ngrokToken:Zc,isNgrokWhitelisted:el}:{}}async function $o(){if(!nn||!wr)return;if(await sl({userAccessKey:nn,projectId:wr}))return nn;let e=`user access key "${nn}" is invalid for project "${wr}"`;throw new P(e)}function Wo(){return $m}function Vo(){return Wm}var on,ot,an,cn,Zc,el,wr,tl,nn,$m,Wm,Hw,Qe=w(()=>{"use strict";pe();Ge();Bt();J();$();he();le();on=C("testim-custom-token"),wr=null,tl=null,Hw=5*60*1e3});var Hm={};G(Hm,{isCi:()=>es});var es,Go=w(()=>{"use strict";es=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var Ae={};G(Ae,{addTestRetry:()=>xl,clearTestResult:()=>Il,deleteCloudflareTunnel:()=>_l,fetchLambdatestConfig:()=>vl,fixGridAppIDStructure:()=>Ml,forceUpdateCloudflareTunnelRoutes:()=>kl,getAllGrids:()=>wl,getAppDetails:()=>pn,getApplitoolsIntegrationData:()=>Cl,getBrowserStackSessionMetaData:()=>sv,getCloudflareTunnel:()=>Pl,getEditorUrl:()=>ev,getGridById:()=>qo,getGridByName:()=>bl,getHybridGridProvider:()=>yl,getLabFeaturesByProjectId:()=>Sl,getMobileDevicesFromGrid:()=>Ll,getRealData:()=>El,getS3Artifact:()=>un,getS3ArtifactText:()=>ol,getSuiteTestList:()=>dl,getTestPlan:()=>Zw,getTestPlanTestList:()=>pl,getTestResults:()=>Sr,getUsageForCurrentBillingPeriod:()=>ml,initializeUserWithAuth:()=>Tl,isTestResultCompleted:()=>fl,keepAliveCompanySlots:()=>Bl,keepAliveGrid:()=>gl,loadSfdcCredential:()=>il,loadTest:()=>al,releaseCompanySlot:()=>Ul,releaseGridSlot:()=>hl,reportExecutionFinished:()=>Ho,reportExecutionStarted:()=>ul,requestCompanySlot:()=>Nl,saveRemoteStep:()=>Rl,saveTestPlanResult:()=>cl,updateCompanySlot:()=>Fl,updateExecutionTests:()=>ll,updateRemoteRunFailure:()=>Ol,updateTestDataArtifact:()=>Ko,updateTestResult:()=>zo,updateTestStatus:()=>vr,uploadAppToGrid:()=>Dl,uploadRunDataArtifact:()=>Al,validateUserAccessKey:()=>sl});async function ts(){let s=await xt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Re({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await ts(),i={...t,...o};return Ve({url:`${fe}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function Yw(s,e,t,r={},n=void 0){let o=await ts(),i={...r,...o};return await js(`${fe}${s||""}`,e,t,i,n)}async function ln(s,e){let t=await ts();return await wc(`${fe}${s||""}`,e,t)}async function Xw(s,e){let t=await ts();return await Bs(`${fe}${s||""}`,e,t)}async function Qw(s,e){let t=await ts();return await $s(`${fe}${s||""}`,e||void 0,t)}async function Se(s,e,t,r){let n=await ts();return await be(`${fe}${s||""}`,e||void 0,n,r,t)}function un(s,e){return(0,Q.default)(()=>Se(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function ol(s){return(0,Q.default)(()=>Qw(`/storage${s}`))}async function Zw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,Q.default)(()=>Se("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function il({branch:s,projectId:e}){let t=await(0,Q.default)(()=>Se(`/branch/branchData/${s}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function al({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,Q.default)(()=>Se(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function cl(s,e,t){return(0,Q.default)(()=>Re({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function vr(s,e,t,r,n,o,i=te){return(0,Q.default)(()=>ln("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:Kw,...o}),{retries:i,factor:1})}function ll(s,e,t,r,n,o,i,a){return(0,Q.default)(()=>ln("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:te,factor:1})}async function ul({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Go(),Hm));return Re({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function Ho(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,Q.default)(()=>ln("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:te,factor:1})}async function pl(s,e,t,r,n){return(0,Q.default)(()=>Re({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function dl({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,Q.default)(()=>Re({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:te,factor:1})}async function pn({appId:s,projectId:e}){try{return await(0,Q.default)(()=>Se(`/mobile-app/app/${s}?projectId=${e}`),{retries:te,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function ml(s){try{return await(0,Q.default)(()=>Se(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){Wt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function fl(s,e,t){return(0,Q.default)(()=>Se(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function Sr(s,e,t,r){return(0,Q.default)(()=>Se(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function gl(s,e){return Re({url:`/grid/keep-alive?reqId=${se()}`,body:{projectId:s,slots:e},timeout:1e4})}function hl(s,e,t,r,n){return Re({url:`/grid/release?reqId=${se()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function yl(s){return Re({url:"/grid/hybrid/provider",body:s})}function bl(s,e,t,r,n){return(0,Q.default)(()=>Se("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:se()}),{retries:te,factor:1})}function qo(s,e,t,r,n){return(0,Q.default)(()=>Se(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:se()}),{retries:te,factor:1})}async function Tl({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:o,gridId:i,grid:a}){var l,c;try{return await(0,Q.default)(()=>Ve({url:`${fe}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:o,gridId:i,gridName:a}}),{retries:te,factor:1})}catch(d){throw Wt.error("error initializing info from server",d),(l=d==null?void 0:d.message)!=null&&l.includes("Bad Request")?new P("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."):(c=d==null?void 0:d.code)!=null&&c.includes("ENOTFOUND")?new P("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):d}}async function ev(){if(Ls)return{editorUrl:Ls};try{return await(0,Q.default)(()=>Se("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch{return Wt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function wl(s){return(0,Q.default)(()=>Se("/grid",{companyId:s}),{retries:te,factor:1})}function El(s,e,t){return(0,Q.default)(()=>Se(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function zo(s,e,t,r,n){return(0,Q.default)(()=>Re({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function Il(s,e,t,r){return(0,Q.default)(()=>Re({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function Rl(s,e,t,r){return(0,Q.default)(()=>Re({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function tv(s){return s.startsWith("/")?s:`/${s}`}function rv(s,e,t){let r=tv(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function zm(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${se()}${i||""}`,l=`${e}/${t}/${a}`,c=rv(l,"test-result-artifacts",s),d=Buffer.from(qm.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,Q.default)(()=>Yw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),c}function xl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,Q.default)(()=>Re({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:te,factor:1})}async function Cl(s){try{return await Se(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Wt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Pl(s,e){try{return await ln("/tunnel",{companyId:s,routes:e})}catch(t){return Wt.warn("could'nt get tunnel.",{err:t}),{}}}async function kl(s,e){try{return await Re({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}async function _l(s,e){try{return await Xw(`/tunnel/${e}`,{companyId:s})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}function Ol(s){return Ve({url:`${fe}/result/remoteRunFailure`,body:s})}async function Ll({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${Jw}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,Q.default)(()=>Se(o,{projectId:s}),{retries:te,factor:1})}catch(i){return Wt.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function Dl({projectId:s,gridId:e,app:t,timeout:r}){return(0,Q.default)(()=>Re({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function Ml(s){return(0,Q.default)(()=>Re({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Nl(s,e){return(0,Q.default)(()=>Re({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Ul(s,e,t){return(0,Q.default)(()=>Re({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Fl(s,e,t){return(0,Q.default)(()=>ln("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Bl(s,e,t){return Re({url:`/slot-management/keep-alive?reqId=${se()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function sv(s,e){return await be(`${Ds}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function sl(s){try{return await Se("/v2/project/validateUserAccessKey",s),!0}catch(e){return Wt.error("error validating user access key",{error:e}),!1}}var er,qm,Q,nl,Kw,Wt,te,Jw,vl,Sl,Al,Ko,he=w(()=>{"use strict";er=S(require("lodash")),qm=S(require("pako"));B();pe();ne();Ge();Qe();Q=S(require("p-retry")),nl=S(require("object-hash"));J();$();Kw=ft(),Wt=C("testim service api"),te=3,Jw="/grid";vl=async()=>(0,Q.default)(()=>Se("/grid/lt/config"),{retries:te,factor:1}),Sl=async s=>(0,Q.default)(()=>Se(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Al=er.memoize(async(s,e,t,r)=>{if(!er.isEmpty(r))return await zm(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,nl.default)(r)}:${e}:${t}`),Ko=er.memoize(async(s,e,t,r,n)=>!r||er.isEmpty(r)?void 0:await zm(s,e,t,JSON.stringify((()=>{let i=er.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{i[l]&&Object.assign(i,{[l]:Cc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,nl.default)(r)}:${e}:${t}`)});async function Km(){let s=await Promise.any(nv.map(async e=>{try{return await be(e)}catch{return null}}));return s==null?void 0:s.ip}var nv,Jm=w(()=>{"use strict";Ge();nv=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});var tr={};G(tr,{getSessionPlayer:()=>Z,options:()=>$l});var Jo,$l,jl,Z,Te=w(()=>{"use strict";Jo=require("path");$();$l={playerPath:void 0},Z=()=>{if(jl)return jl;let s=($e(),Ne(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(tn(),Ne(en)),t=e(),r=$l.playerPath?(0,Jo.resolve)($l.playerPath,"src/background/sessionPlayerInit.ts"):(0,Jo.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),jl=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(cc),n}});function av(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(Te(),Ne(tr)).getSessionPlayer()}catch{}})}async function dn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:o,useChromeLauncher:i,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(o||i),u=d?iv:ov,f=null;if(D.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{f=await Km()}catch(y){Ym.error("failed to get public ip",y)}let g=!0;N("before initializeUserWithAuth");let h=await yt(async()=>(av(a),g=!1,await Tl({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:f,gridId:l,grid:c})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:f})();return s.publicIps=[h.clientPublicIp],N("after initializeUserWithAuth"),f&&h.clientPublicIp&&h.clientPublicIp!==f&&(Ym.error("public ip mismatch",{publicIpFromExternalService:f,publicIpFromServices:h.clientPublicIp}),s.publicIps.push(f)),Gm(h.authData,{projectId:e,token:t,userAccessKey:r,publicIp:h.clientPublicIp,initializedFromCache:g}),h}var Ym,ov,iv,Xm=w(()=>{"use strict";$e();he();Bt();Qe();Jm();ne();$();le();Ym=C("initializeUserWithAuth"),ov=1e3*60*5,iv=1e3*60*60*10});async function ef(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Bo():s.chromeBinaryLocation,e=Zs({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==q.EXTENSION&&await Tr(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await zc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await qc(s.installCustomExtension,n)}return await e,t}async function tf(s){var i;cv.info("prepare MockNetwork",{location:s});let e=await Ic(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Qm*1e6)throw new Error(`${Wl} exceeded ${Qm}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Wl} cannot be parsed.${Yo.EOL}${a}`)}let n=new Zm.default;if(!n.validate(Uc,r)){let a=(i=n.errors)==null?void 0:i.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Yo.EOL);throw new Error(`${Wl} is malformed.${Yo.EOL}${a}`)}return r.entries}var Yo,Zm,Qm,Wl,cv,Vl=w(()=>{"use strict";Yo=S(require("os"));B();sm();tn();Zm=S(require("ajv"));ne();Xc();Xm();Qm=1,Wl="JSON file supplied to --mock-network-pattern",cv=($(),Ne(dc)).getLogger("prepare runner")});function sf(s,e=process){async function t(r){await ce(ie(rf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{mn.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(mn.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{mn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw mn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw mn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function rs(s){rf.push(s)}var mn,rf,fn=w(()=>{"use strict";$();B();mn=C("process-handler"),rf=[]});function zl(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?Td:Fr}/extension/testim-headless${t}`,n=D.flags.useMV3Extension.isEnabled({projectId:s.project});return!s.headlessExtensionDownloadPath&&n&&(s.headlessExtensionDownloadPath=`${Fr}/extension/testim-headless-mv3${t}`),s.headlessExtensionDownloadPath&&(r=s.headlessExtensionDownloadPath),{chrome:r,"edge-chromium":r}}function lf(s){let{chrome:e}=zl(s,!1);return e}function Qo(s){let e=`${Fr}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Zo=w(()=>{"use strict";pe();le()});function ff(s){_e||(s!=null&&s.userId||(s={anonymousId:mf}),df.identify(s))}function bt(s,e){return gn("ci",s,e)}function gn(s,e,t){if(_e)return;let r=s?{userId:s}:{anonymousId:mf};df.track(Object.assign(r,{event:e,properties:t}))}var pf,df,mf,ss=w(()=>{"use strict";pe();pf=require("@segment/analytics-node"),df=new pf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),mf=require("crypto").randomBytes(20).toString("hex")});function gf(s){return s.start&&gn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function hf(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new P("Agent port is not number");let t=Qo(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var yf=w(()=>{"use strict";Zo();ss();J()});var bf,gv,hv,Kl,Tf=w(()=>{"use strict";bf="TST_CREDS",gv=["username","password"],hv="$encrypted",Kl={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of gv)t[r]={[hv]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(bf)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[bf]:this.proxyPlaceholder})}}});async function vf(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:se()}))]}:await dl({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 Jl(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Yl(s,e){let t=s.mode===q.EXTENSION?Er:yn,r=wf.difference(Gs(s,e),t);if(r.length>0)throw bt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var wf,Er,yn,ei=w(()=>{"use strict";wf=S(require("lodash"));B();ss();he();J();ne();Er=["edge-chromium","chrome"],yn=[...Er,"firefox","safari","safari technology preview"]});function ri(s){let{platform:e}=process;e==="win32"?(0,ti.exec)(`start chrome ${s}`):e==="darwin"?(0,ti.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,ti.exec)(`google-chrome ${s}`)}var ti,Xl=w(()=>{"use strict";ti=require("child_process")});var ru={};G(ru,{doLogin:()=>tu,getProjectId:()=>yv,getToken:()=>bv});async function yv(){return If("projectId")}async function bv(){return If("token")}function Ef(s,e){return Promise.race([s,ae(e).then(()=>{throw new oe("timeout")})])}async function Tv(){let s=(await import("express")).default(),e=async function(){return Ef(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(he(),Ae)),{editorUrl:n}=await r();ri(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function tu({overwriteExisting:s=!0,projects:e=null}={}){let t=Ql.homedir(),r=Zl.join(t,".testim");if(await ge(r)&&!s)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Ef(Tv(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,l.succeed(),await Sf(r,o);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await i({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}))});o.token=c.project.ci.token,o.projectId=c.project.id,await Sf(r,o);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Sf(s,e){await eu.promises.writeFile(s,si.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function If(s){let e=Ql.homedir(),t=Zl.join(e,".testim"),r=await ge(t),n={};if(r)try{n=si.parse((await eu.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Ql,Zl,si,eu,ni=w(()=>{"use strict";Ql=S(require("os")),Zl=S(require("path")),si=S(require("yaml"));B();eu=require("fs");J();Xl()});var Of={};G(Of,{process:()=>xv});var nu,Cf,oi,Pf,Vt,Me,kf,wv,De,au,vv,Sv,Af,_f,Ev,ou,iu,cu,su,Ct,Iv,p,Rv,Av,xf,xv,Lf=w(()=>{"use strict";nu=S(require("ms")),Cf=S(require("chalk")),oi=S(require("fs")),Pf=S(require("url")),Vt=S(require("lodash")),Me=S(require("path"));B();Zo();yf();Bt();kf=require("commander");ne();J();Ur();B();le();Tf();ei();wv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),De=(s,e)=>(e.push(s),e),au=new kf.Command,vv=s=>s.split(","),Sv=(s,e)=>!s||s.length===0?e:s,Af=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],_f=()=>{function s(h){return h.includes("-h, --help")}function e(h){return h.includes("--params [params-json-string]")}function t(h){return h.includes("--ext")||h.includes("--extension-path")||h.includes("--headless-extension-download-path")}function r(h){return h.includes("--player-path")||h.includes("--player-require-path")}function n(h){return h.includes("--executionId")||h.includes("--source")||h.includes("--resultId")||h.includes("--remoteRunId")||h.includes("--schedulerId")}function o(h){return h.includes("--get-browser-timeout")||h.includes("--get-browser-retries")||h.includes("--get-session-timeout")||h.includes("--get-session-retries")||h.includes("--driver-request-timeout")||h.includes("--driver-request-retries")}function i(h){return h.includes("--user")}function a(h){return h.includes("shouldMonitorPerformance")}function l(h){return h.includes("--save-rca-locally")}function c(h){return h.includes("--exit-code-ignore-failing-tests")}function d(h){return h.includes("--high-speed")}function m(h){return h.includes("--urls")}function u(h){return h.includes("--test-start-timeout")}function f(h){return h.includes("--install-lazy-deps")}function g(h){return h.includes("--print-final-caps")||h.includes("--print-grids")}au.help(h=>h.split(`
|
|
17
|
-
`).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!i(T)&&!o(T)&&!l(T)&&!c(T)&&!d(T)&&!m(T)&&!u(T)&&!f(T)&&!
|
|
18
|
-
`))},
|
|
16
|
+
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),i}}async function jw(){let s=`${Fr}/extension/sessionPlayer_LATEST_RELEASE`;return(await Nt(s)).body.toString("utf8")}async function $w(s,e){if(!ke(s)||ke(s)&&e||_e)return s;let t=await jw();return`${s}-${t}`}function Kc(){let s=ft();return Zr.resolve(s,"testim-bin")}function Ww(){let s=Kc();return Zr.resolve(s,"sessionPlayer.zip")}async function Fm(s,e,t=!1){try{return await bo(s,e),await nt(e,Kc())}catch(r){if(t)throw r;return await Fm(s,e,!0)}}async function br(s,e){Uo.info("prepare player",{location:s,canary:e});let t=Ww();return ht(async()=>{let r=await $w(s,e);return await Fm(r,t),{}},"preparePlayer",Um,[s,e,t])()}var Dm,Mm,Zr,Nm,Uo,Um,Hc,Lm,tn=w(()=>{"use strict";Dm=S(require("ms")),Mm=S(require("fs")),Zr=S(require("path"));pe();Bt();Nm=require("serialize-error");$();Bc();K();B();Uo=C("prepare runner and testim start"),Um=(0,Dm.default)("0.5 day"),Hc=16,Lm=`The size of the custom extension is more than ${Hc}MB`});function Vw(){let s=rn.type().toLowerCase();return s==="darwin"?rn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?rn.arch()==="x64"?"win64":"win32":"linux"}async function Bo(){let s=Vw(),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 P(`Unsupported platform: ${s}`);let r=parseInt(sn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${sn}/${n[s]}.zip`,a=Fo.join(Jc,n[s]),l=`${a}.zip`,c=Fo.join(a,o[s]);if(await ge(c))return c;if(!await ge(l)){let m=(0,Yc.default)("Downloading Chromium").start();try{await Bm.promises.mkdir(Jc),await Je(i,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,Yc.default)("Extracting Chromium").start();try{await nt(l,Jc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Bm,rn,Fo,Yc,sn,Jc,Xc=w(()=>{"use strict";Bm=S(require("fs")),rn=S(require("os")),Fo=S(require("path")),Yc=S(require("ora"));K();B();sn="1000968",Jc=Fo.join(Ft,`chrome-${sn}`)});async function Wm(s,e){return Tr=s,tl=e,await Qc()}function Vm(s,e){Tr=e.projectId,tl=e.token,nn=e.userAccessKey,ot=s.token,an=rl(ot),cn=s.refreshToken,Zc=s.ngrokToken,el=s.isNgrokWhitelisted,jm=e.publicIp,$m=e.initializedFromCache}function Hw(s=Tr,e=tl){return ht(()=>(on.info("request to get cli token from server"),Ve({url:`${fe}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Gw*10,{projectId:s,token:e})()}async function qw(){on.info("request to refresh JWT cli token from server");let s=await Ve({url:`${fe}/auth/refreshToken`,body:{token:ot,refreshToken:cn}});return ot=s.token,an=rl(ot),s.refreshToken&&(cn=s.refreshToken),ot}async function Qc(){try{let s=await Hw();return on.info("successfully get cli token from server"),ot=s.token,an=rl(ot),cn=s.refreshToken,Zc=s.ngrokToken,el=s.isNgrokWhitelisted,ot}catch(s){throw s.message.includes("Unauthorized")?new P("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."):(on.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Tr}),new P(`While trying to retrieve CLI token, caught error: ${s}`))}}function rl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function xt(){if(!an)return Qc();let s=D.flags.accessTokenExpiryMargin.getValue();if(an<Date.now()+4*s)try{return await qw()}catch(e){return on.error("failed to refresh token, executing fallback",e),Qc()}return ot}function jo(){return cn}function jt(){return ot?{uid:require("jsonwebtoken").decode(ot).id,ngrokToken:Zc,isNgrokWhitelisted:el}:{}}async function $o(){if(!nn||!Tr)return;if(await sl({userAccessKey:nn,projectId:Tr}))return nn;let e=`user access key "${nn}" is invalid for project "${Tr}"`;throw new P(e)}function Wo(){return jm}function Vo(){return $m}var on,ot,an,cn,Zc,el,Tr,tl,nn,jm,$m,Gw,Qe=w(()=>{"use strict";pe();Ge();Bt();K();$();he();le();on=C("testim-custom-token"),Tr=null,tl=null,Gw=5*60*1e3});var Gm={};H(Gm,{isCi:()=>es});var es,Go=w(()=>{"use strict";es=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var Ae={};H(Ae,{addTestRetry:()=>xl,clearTestResult:()=>Il,deleteCloudflareTunnel:()=>_l,fetchLambdatestConfig:()=>vl,fixGridAppIDStructure:()=>Ml,forceUpdateCloudflareTunnelRoutes:()=>kl,getAllGrids:()=>wl,getAppDetails:()=>pn,getApplitoolsIntegrationData:()=>Cl,getBrowserStackSessionMetaData:()=>rv,getCloudflareTunnel:()=>Pl,getEditorUrl:()=>Zw,getGridById:()=>qo,getGridByName:()=>bl,getHybridGridProvider:()=>yl,getLabFeaturesByProjectId:()=>Sl,getMobileDevicesFromGrid:()=>Ll,getRealData:()=>El,getS3Artifact:()=>un,getS3ArtifactText:()=>ol,getSuiteTestList:()=>dl,getTestPlan:()=>Qw,getTestPlanTestList:()=>pl,getTestResults:()=>vr,getUsageForCurrentBillingPeriod:()=>ml,initializeUserWithAuth:()=>Tl,isTestResultCompleted:()=>fl,keepAliveCompanySlots:()=>Bl,keepAliveGrid:()=>gl,loadSfdcCredential:()=>il,loadTest:()=>al,releaseCompanySlot:()=>Ul,releaseGridSlot:()=>hl,reportExecutionFinished:()=>Ho,reportExecutionStarted:()=>ul,requestCompanySlot:()=>Nl,saveRemoteStep:()=>Rl,saveTestPlanResult:()=>cl,updateCompanySlot:()=>Fl,updateExecutionTests:()=>ll,updateRemoteRunFailure:()=>Ol,updateTestDataArtifact:()=>Ko,updateTestResult:()=>zo,updateTestStatus:()=>wr,uploadAppToGrid:()=>Dl,uploadRunDataArtifact:()=>Al,validateUserAccessKey:()=>sl});async function ts(){let s=await xt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Re({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await ts(),i={...t,...o};return Ve({url:`${fe}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function Jw(s,e,t,r={},n=void 0){let o=await ts(),i={...r,...o};return await js(`${fe}${s||""}`,e,t,i,n)}async function ln(s,e){let t=await ts();return await wc(`${fe}${s||""}`,e,t)}async function Yw(s,e){let t=await ts();return await Bs(`${fe}${s||""}`,e,t)}async function Xw(s,e){let t=await ts();return await $s(`${fe}${s||""}`,e||void 0,t)}async function Se(s,e,t,r){let n=await ts();return await be(`${fe}${s||""}`,e||void 0,n,r,t)}function un(s,e){return(0,Q.default)(()=>Se(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function ol(s){return(0,Q.default)(()=>Xw(`/storage${s}`))}async function Qw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,Q.default)(()=>Se("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function il({branch:s,projectId:e}){let t=await(0,Q.default)(()=>Se(`/branch/branchData/${s}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function al({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,Q.default)(()=>Se(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function cl(s,e,t){return(0,Q.default)(()=>Re({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function wr(s,e,t,r,n,o,i=te){return(0,Q.default)(()=>ln("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:zw,...o}),{retries:i,factor:1})}function ll(s,e,t,r,n,o,i,a){return(0,Q.default)(()=>ln("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:te,factor:1})}async function ul({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Go(),Gm));return Re({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function Ho(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,Q.default)(()=>ln("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:te,factor:1})}async function pl(s,e,t,r,n){return(0,Q.default)(()=>Re({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function dl({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,Q.default)(()=>Re({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:te,factor:1})}async function pn({appId:s,projectId:e}){try{return await(0,Q.default)(()=>Se(`/mobile-app/app/${s}?projectId=${e}`),{retries:te,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function ml(s){try{return await(0,Q.default)(()=>Se(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){Wt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function fl(s,e,t){return(0,Q.default)(()=>Se(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function vr(s,e,t,r){return(0,Q.default)(()=>Se(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function gl(s,e){return Re({url:`/grid/keep-alive?reqId=${se()}`,body:{projectId:s,slots:e},timeout:1e4})}function hl(s,e,t,r,n){return Re({url:`/grid/release?reqId=${se()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function yl(s){return Re({url:"/grid/hybrid/provider",body:s})}function bl(s,e,t,r,n){return(0,Q.default)(()=>Se("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:se()}),{retries:te,factor:1})}function qo(s,e,t,r,n){return(0,Q.default)(()=>Se(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:se()}),{retries:te,factor:1})}async function Tl({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:o,gridId:i,grid:a}){var l,c;try{return await(0,Q.default)(()=>Ve({url:`${fe}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:o,gridId:i,gridName:a}}),{retries:te,factor:1})}catch(d){throw Wt.error("error initializing info from server",d),(l=d==null?void 0:d.message)!=null&&l.includes("Bad Request")?new P("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."):(c=d==null?void 0:d.code)!=null&&c.includes("ENOTFOUND")?new P("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):d}}async function Zw(){if(Ls)return{editorUrl:Ls};try{return await(0,Q.default)(()=>Se("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch{return Wt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function wl(s){return(0,Q.default)(()=>Se("/grid",{companyId:s}),{retries:te,factor:1})}function El(s,e,t){return(0,Q.default)(()=>Se(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function zo(s,e,t,r,n){return(0,Q.default)(()=>Re({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function Il(s,e,t,r){return(0,Q.default)(()=>Re({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function Rl(s,e,t,r){return(0,Q.default)(()=>Re({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function ev(s){return s.startsWith("/")?s:`/${s}`}function tv(s,e,t){let r=ev(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function qm(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${se()}${i||""}`,l=`${e}/${t}/${a}`,c=tv(l,"test-result-artifacts",s),d=Buffer.from(Hm.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,Q.default)(()=>Jw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),c}function xl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,Q.default)(()=>Re({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:te,factor:1})}async function Cl(s){try{return await Se(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Wt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Pl(s,e){try{return await ln("/tunnel",{companyId:s,routes:e})}catch(t){return Wt.warn("could'nt get tunnel.",{err:t}),{}}}async function kl(s,e){try{return await Re({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}async function _l(s,e){try{return await Yw(`/tunnel/${e}`,{companyId:s})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}function Ol(s){return Ve({url:`${fe}/result/remoteRunFailure`,body:s})}async function Ll({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${Kw}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,Q.default)(()=>Se(o,{projectId:s}),{retries:te,factor:1})}catch(i){return Wt.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function Dl({projectId:s,gridId:e,app:t,timeout:r}){return(0,Q.default)(()=>Re({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function Ml(s){return(0,Q.default)(()=>Re({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Nl(s,e){return(0,Q.default)(()=>Re({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Ul(s,e,t){return(0,Q.default)(()=>Re({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Fl(s,e,t){return(0,Q.default)(()=>ln("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Bl(s,e,t){return Re({url:`/slot-management/keep-alive?reqId=${se()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function rv(s,e){return await be(`${Ds}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function sl(s){try{return await Se("/v2/project/validateUserAccessKey",s),!0}catch(e){return Wt.error("error validating user access key",{error:e}),!1}}var er,Hm,Q,nl,zw,Wt,te,Kw,vl,Sl,Al,Ko,he=w(()=>{"use strict";er=S(require("lodash")),Hm=S(require("pako"));B();pe();ne();Ge();Qe();Q=S(require("p-retry")),nl=S(require("object-hash"));K();$();zw=mt(),Wt=C("testim service api"),te=3,Kw="/grid";vl=async()=>(0,Q.default)(()=>Se("/grid/lt/config"),{retries:te,factor:1}),Sl=async s=>(0,Q.default)(()=>Se(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Al=er.memoize(async(s,e,t,r)=>{if(!er.isEmpty(r))return await qm(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,nl.default)(r)}:${e}:${t}`),Ko=er.memoize(async(s,e,t,r,n)=>!r||er.isEmpty(r)?void 0:await qm(s,e,t,JSON.stringify((()=>{let i=er.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{i[l]&&Object.assign(i,{[l]:Cc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,nl.default)(r)}:${e}:${t}`)});async function zm(){let s=await Promise.any(sv.map(async e=>{try{return await be(e)}catch{return null}}));return s==null?void 0:s.ip}var sv,Km=w(()=>{"use strict";Ge();sv=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});var tr={};H(tr,{getSessionPlayer:()=>Z,options:()=>$l});var Jo,$l,jl,Z,Te=w(()=>{"use strict";Jo=require("path");$();$l={playerPath:void 0},Z=()=>{if(jl)return jl;let s=($e(),Ne(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(tn(),Ne(en)),t=e(),r=$l.playerPath?(0,Jo.resolve)($l.playerPath,"src/background/sessionPlayerInit.ts"):(0,Jo.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),jl=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(cc),n}});function iv(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(Te(),Ne(tr)).getSessionPlayer()}catch{}})}async function dn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:o,useChromeLauncher:i,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(o||i),u=d?ov:nv,f=null;if(D.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{f=await zm()}catch(y){Jm.error("failed to get public ip",y)}let h=!0;N("before initializeUserWithAuth");let g=await ht(async()=>(iv(a),h=!1,await Tl({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:f,gridId:l,grid:c})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:f})();return s.publicIps=[g.clientPublicIp],N("after initializeUserWithAuth"),f&&g.clientPublicIp&&g.clientPublicIp!==f&&(Jm.error("public ip mismatch",{publicIpFromExternalService:f,publicIpFromServices:g.clientPublicIp}),s.publicIps.push(f)),Vm(g.authData,{projectId:e,token:t,userAccessKey:r,publicIp:g.clientPublicIp,initializedFromCache:h}),g}var Jm,nv,ov,Ym=w(()=>{"use strict";$e();he();Bt();Qe();Km();ne();$();le();Jm=C("initializeUserWithAuth"),nv=1e3*60*5,ov=1e3*60*60*10});async function Zm(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Bo():s.chromeBinaryLocation,e=Zs({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==q.EXTENSION&&await br(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await zc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await qc(s.installCustomExtension,n)}return await e,t}async function ef(s){var i;av.info("prepare MockNetwork",{location:s});let e=await Ic(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Xm*1e6)throw new Error(`${Wl} exceeded ${Xm}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Wl} cannot be parsed.${Yo.EOL}${a}`)}let n=new Qm.default;if(!n.validate(Uc,r)){let a=(i=n.errors)==null?void 0:i.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Yo.EOL);throw new Error(`${Wl} is malformed.${Yo.EOL}${a}`)}return r.entries}var Yo,Qm,Xm,Wl,av,Vl=w(()=>{"use strict";Yo=S(require("os"));B();rm();tn();Qm=S(require("ajv"));ne();Xc();Ym();Xm=1,Wl="JSON file supplied to --mock-network-pattern",av=($(),Ne(dc)).getLogger("prepare runner")});function rf(s,e=process){async function t(r){await ce(ie(tf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{mn.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(mn.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{mn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw mn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw mn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function rs(s){tf.push(s)}var mn,tf,fn=w(()=>{"use strict";$();B();mn=C("process-handler"),tf=[]});function zl(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?bd:Fr}/extension/testim-headless${t}`,n=D.flags.useMV3Extension.isEnabled({projectId:s.project});return!s.headlessExtensionDownloadPath&&n&&(s.headlessExtensionDownloadPath=`${Fr}/extension/testim-headless-mv3${t}`),s.headlessExtensionDownloadPath&&(r=s.headlessExtensionDownloadPath),{chrome:r,"edge-chromium":r}}function cf(s){let{chrome:e}=zl(s,!1);return e}function Qo(s){let e=`${Fr}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Zo=w(()=>{"use strict";pe();le()});function mf(s){_e||(s!=null&&s.userId||(s={anonymousId:df}),pf.identify(s))}function yt(s,e){return gn("ci",s,e)}function gn(s,e,t){if(_e)return;let r=s?{userId:s}:{anonymousId:df};pf.track(Object.assign(r,{event:e,properties:t}))}var uf,pf,df,ss=w(()=>{"use strict";pe();uf=require("@segment/analytics-node"),pf=new uf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),df=require("crypto").randomBytes(20).toString("hex")});function ff(s){return s.start&&gn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function gf(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new P("Agent port is not number");let t=Qo(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var hf=w(()=>{"use strict";Zo();ss();K()});var yf,fv,gv,Kl,bf=w(()=>{"use strict";yf="TST_CREDS",fv=["username","password"],gv="$encrypted",Kl={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of fv)t[r]={[gv]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(yf)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[yf]:this.proxyPlaceholder})}}});async function wf(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:se()}))]}:await dl({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 Jl(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Yl(s,e){let t=s.mode===q.EXTENSION?Sr:yn,r=Tf.difference(Gs(s,e),t);if(r.length>0)throw yt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Tf,Sr,yn,ei=w(()=>{"use strict";Tf=S(require("lodash"));B();ss();he();K();ne();Sr=["edge-chromium","chrome"],yn=[...Sr,"firefox","safari","safari technology preview"]});function ri(s){let{platform:e}=process;e==="win32"?(0,ti.exec)(`start chrome ${s}`):e==="darwin"?(0,ti.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,ti.exec)(`google-chrome ${s}`)}var ti,Xl=w(()=>{"use strict";ti=require("child_process")});var ru={};H(ru,{doLogin:()=>tu,getProjectId:()=>hv,getToken:()=>yv});async function hv(){return Ef("projectId")}async function yv(){return Ef("token")}function Sf(s,e){return Promise.race([s,ae(e).then(()=>{throw new oe("timeout")})])}async function bv(){let s=(await import("express")).default(),e=async function(){return Sf(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(he(),Ae)),{editorUrl:n}=await r();ri(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function tu({overwriteExisting:s=!0,projects:e=null}={}){let t=Ql.homedir(),r=Zl.join(t,".testim");if(await ge(r)&&!s)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Sf(bv(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,l.succeed(),await vf(r,o);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await i({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}))});o.token=c.project.ci.token,o.projectId=c.project.id,await vf(r,o);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function vf(s,e){await eu.promises.writeFile(s,si.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function Ef(s){let e=Ql.homedir(),t=Zl.join(e,".testim"),r=await ge(t),n={};if(r)try{n=si.parse((await eu.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Ql,Zl,si,eu,ni=w(()=>{"use strict";Ql=S(require("os")),Zl=S(require("path")),si=S(require("yaml"));B();eu=require("fs");K();Xl()});var _f={};H(_f,{process:()=>Av});var nu,xf,oi,Cf,Vt,Me,Pf,Tv,De,au,wv,vv,Rf,kf,Sv,ou,iu,cu,su,Ct,Ev,p,Iv,Rv,Af,Av,Of=w(()=>{"use strict";nu=S(require("ms")),xf=S(require("chalk")),oi=S(require("fs")),Cf=S(require("url")),Vt=S(require("lodash")),Me=S(require("path"));B();Zo();hf();Bt();Pf=require("commander");ne();K();Ur();B();le();bf();ei();Tv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),De=(s,e)=>(e.push(s),e),au=new Pf.Command,wv=s=>s.split(","),vv=(s,e)=>!s||s.length===0?e:s,Rf=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],kf=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function o(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 i(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}au.help(g=>g.split(`
|
|
17
|
+
`).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!i(T)&&!o(T)&&!l(T)&&!c(T)&&!d(T)&&!m(T)&&!u(T)&&!f(T)&&!h(T)).join(`
|
|
18
|
+
`))},Sv=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(xf.default.yellow(`
|
|
19
19
|
WARNING: ${s} is deprecated. ${t}
|
|
20
|
-
`))},ou=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:iu,argv:cu,exit:su,cwd:Ct}=global.process,Iv=["trace","debug","info","warn","error","silent"];_c(cu,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));au.description("Testim.io CLI").option("-h --help","output usage information",_f).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",De,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",De,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",De,[]).option("--test-id [test-id]","test ID to run",De,[]).option("-l, --label [label]","labels to search test by",De,[]).option("-n, --name [test-name]","test name to run",De,[]).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",vv).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",De,[]).option("--test-plan-id [test-plan-id]","test plan to run",De,[]).option("--suite [suite-name]","suite to run",De,[]).option("--suite-id [suite-id]","suite ID to run",De,[]).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",De,[]).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(iu.TESTIM_TEST_START_TIMEOUT)||2*60*1e3).option("--timeout [test-timeout]","Test run timeout in milliseconds",Number).option("--browser-timeout [open-browser-timeout]","Get browser from grid timeout in milliseconds",Number).option("--new-browser-wait-timeout [max-wait-to-browser]","Maximum get browser wait in minutes",Number).option("--get-browser-timeout [get-browser-timeout]","Timeout for a single attempt to get browser from the grid configured in the project's plan",Number).option("--get-browser-retries [get-browser-retries]","Number of attempts to get browser from the grid configured in the project's plan",Number).option("--get-session-timeout [get-session-timeout]",'Timeout for "/session" request to the selenium server',Number,(0,nu.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,nu.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: ${ou.join("/")}`,De,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",De,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",De,[]).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)",De,[]).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)",De,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").parse(cu);p=au.opts(),Rv=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},Av=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},xf=s=>{var r;if(!D.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=oi.readFileSync(s);(r=Kl)!=null&&r.containsEncryptedCredentials(t.toString())&&Kl.injectProxyCredentialsStoreToGlobal()},xv=async()=>{var T,E,b,v,R,I,L,U;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!cu.slice(2).length)throw _f(),new jr;if(p.version){let A="Testim CLI Version: ";iu.npm_package_version&&(console.log(A,iu.npm_package_version),su(0));let x=ft();x&&(console.log(A,x),su(0)),console.log("Could not find version, please check the package.json manually"),su(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&gm(),p.clearFileCache&&Yr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let A=Me.resolve(n);mm(A)}if(p.usePrefechedData&&hm(),p.playerRequirePath){let A=Me.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",A);let x=Me.join(A,"tsconfig.node.json"),F=require("ts-node").register({project:x,ignore:[/node_modules/,new RegExp(`^${Vt.escapeRegExp(Me.relative(Ct(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:F.config.options.paths,baseUrl:F.config.options.baseUrl}),(Te(),Ne(tr)).options.playerPath=A;let z=require("module"),X=z.prototype.require;z.prototype.require=function(tt){return tt==="rox-alias"?X.call(this,"rox-node"):tt==="canvas"?{}:X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=oi.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new P("missing --proxy option");if(gf(p))return hf(p);try{let A={};p.configFile?(xf(p.configFile),A=require(Me.join(Ct(),p.configFile)).config):p.optionsFile&&(A=require(Me.join(Ct(),p.optionsFile))),A&&typeof A.then=="function"&&(A=await A),Object.keys(A).forEach(x=>{let k=wv(x);p[k]=Sv(p[k],A[x])})}catch(A){throw A.message=`Unable to read options file: ${A.message}`,A}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((T=p.testConfig)==null?void 0:T.length)||((E=p.testConfigId)==null?void 0:E.length),i=((b=p.testPlan)==null?void 0:b.length)||((v=p.testPlanId)==null?void 0:v.length),a=((R=p.suite)==null?void 0:R.length)||((I=p.suiteId)==null?void 0:I.length);if(p.seleniumCapsFile)try{r=require(Me.join(Ct(),p.seleniumCapsFile))}catch(A){throw new P(`Failed to parse selenium caps file file error: ${A.message}`)}if((L=p.reporters)!=null&&L.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Me.join(Ct(),p.chromeExtraPrefs))}catch(A){throw new P(`Failed to read/open chrome extra prefs file error: ${A.message}`)}if(p.chromeExtraArgs){let A=p.chromeExtraArgs.split(",");for(let x of A){let[k]=x.split("=");Af.includes(k)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(x),k==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${k}), allowed values: ${JSON.stringify(Af)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&xf(p.paramsFile),s={...s,...require(Me.join(Ct(),p.paramsFile))}}catch(A){throw new P(`Failed to read/open params file error: ${A.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(A){throw new P(`Failed to parse params string error: ${A.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(Rv(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let A=require(Me.join(Ct(),p.sauceOptions)),x=A.platformName&&["ios","android"].includes(A.platformName.toLowerCase());if(A.browserName){let F=A.browserName.toLowerCase();switch(F){case"microsoftedge":p.browser="edge";break;default:p.browser=F}}p.browser==="edge"&&parseFloat(A.version)>=79&&(p.browser="edge-chromium");let k=parseFloat(A.version)<50&&!["dev","beta"].includes(A.version);if(!x&&p.browser==="chrome"&&k)throw new P("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...A}}catch(A){throw new P(`Failed to parse saucelabs options file error: ${A.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(Av(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let A=require(Me.join(Ct(),p.browserstackOptions)),x=A.platform&&["mac","android"].includes(A.platform.toLowerCase());if(A.browserName&&(p.browser=A.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(A.browser_version)>=79&&(p.browser="edge-chromium"),!x&&parseFloat(A.browser_version)<50&&p.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...A}}catch(A){throw new P(`Failed to parse browserstack options file error: ${A.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let A=require(Me.join(Ct(),p.perfectoOptions)),x={location:"US East",securityToken:p.perfectoToken};p.perfecto={...x,...A}}catch(A){throw new P(`Failed to parse perfecto options file error: ${A.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let A=require(Me.join(Ct(),p.testobjectOptions)),x={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...x,...A}}catch(A){throw new P(`Failed to parse test object options file error: ${A.message}`)}if(!p.project){let x=await(await Promise.resolve().then(()=>(ni(),ru))).getProjectId();if(x)p.project=x;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}D.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let x=await(await Promise.resolve().then(()=>(ni(),ru))).getToken();if(x)p.token=x;else throw new P("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let d=A=>A<=0||!Number.isInteger(A);if(d(p.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new P(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Er,...yn].includes(p.browser))throw new P(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new P("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!Iv.includes(p.appiumLogLevel))throw new P(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new P("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(!i&&(p.beforeParallel!==1||p.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if((U=p.host)!=null&&U.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Pf.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(x=>x.trim()).filter(Boolean);let A=p.resultLabel.filter(x=>x.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&hr()&&p.resultLabel.unshift(hr()),A.length)throw new P("A result label cannot exceed 250 characters")}let u=lf(p),f=Qo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new P("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||i))throw new P("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!Vt.inRange(Vt.parseInt(p.setRetention),1,11))throw new P("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let g="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new P(`--mock-network-har ${g}`);if(p.mockNetworkPattern)throw new P(`--mock-network-pattern ${g}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Vt.difference(p.codeCoverageReporter,ou).length){let A=Vt.difference(p.codeCoverageReporter,ou);throw new P(`invalid --code-coverage-reporter parameters ${A.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let h={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(h).filter(A=>Boolean(p[A]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&y.length){let A=y.length>1?"are":"is";throw new P(`${y.map(x=>h[x]).join(" and ")} ${A} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let A=oi.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(A)}catch(A){throw new P(`failed to parse field file error: ${A.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new P("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(Ev("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new P("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new P("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let A={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},x=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...A,...x}}catch(A){throw new P(`failed to parse lightweightMode settings error: ${A.message}`)}else p.turboMode&&![q.APPIUM,q.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
|
|
21
|
-
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?hr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionLocation:[p.extensionPath||u].flat(),extensionPath:p.extensionPath,headlessExtensionDownloadPath:p.headlessExtensionDownloadPath,playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var Uf={};G(Uf,{installAllLazyDependencies:()=>kv,lazyRequire:()=>it});async function it(s,e={}){let t=Wc(s);if(t)return t;let r;e.silent||(r=(0,Df.default)(`Installing ${s} before first usage...`).start());try{let n=await Pv(s);return r&&r.succeed(),n}catch(n){Cv.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Nf(s),i=`${s}@${o}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${i}`;throw r&&r.fail(c),n}}async function Pv(s){return ns.has(s)||(ns.set(s,Mf(s)),ns.get(s).catch(()=>{ns.delete(s)})),ns.get(s)}async function Mf(s){let e=Wc(s);if(e)return e;let t=Nf(s),r=`${s}@${t}`;return await Do(gt(),r),Zt(s)}async function kv(){let s=Object.keys(Xa);for(let e of s)await Mf(e)}function Nf(s){let e=Object.entries(Xa).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Df,Cv,ns,bn=w(()=>{"use strict";Df=S(require("ora"));Qr();$();B();io();Qs();Cv=C("lazy-require"),ns=new Map});var Bf={};G(Bf,{preloadTests:()=>Tn});async function Tn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await yt(async()=>{let t=await ie(s.testId,r=>al({...e,testId:r}),{concurrency:2});return Ff.keyBy(t,"testData.id")},"loadTests",_v,[e,s.testId])()}var Ff,_v,ii=w(()=>{"use strict";Ff=S(require("lodash"));Bt();he();B();_v=1e3*60*60*10});function lu(){return ft()}async function Wf(){if(!_e)try{let s=await ce(Lv(),5e3,"The API call to NPM timed out"),e=lu();e&&$f.lt(e,s)&&console.log(jf.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){Ov.warn("Failed to get NPM version",{err:s})}}var jf,$f,Ov,Lv,uu=w(()=>{"use strict";jf=S(require("chalk")),$f=S(require("semver"));B();pe();Qr();Bt();$();Ov=C("npm-driver"),Lv=yt(()=>vm("@testim/testim-cli"),"getNpmVersion")});var pu,Mv,os,Vf,Gf,du,Hf,qf=w(()=>{"use strict";B();J();$();bn();pu=C("testimNgrok"),Mv=".whitelisted-ngrok.testim.io",os="",Gf=async(s,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${se()}-${s.projectData.projectId}${Mv}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let o=await(await it("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(pu.info("replace https to http"),os=o.replace("https://","http://")):os=o,s.tunnelDiagnostics&&du(),s.baseUrl=os},du=async(s=!0)=>{try{let t=(await it("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===os);console.log("ngrok stats",n),pu.info("ngrok stats",{tunnel:n})}catch(e){pu.error("error collecting ngrok stats",{err:e})}s&&(Vf=setTimeout(()=>du(),1e4))},Hf=async s=>{if(!os)return;clearTimeout(Vf),s.tunnelDiagnostics&&await du(!1),await(await it("ngrok")).disconnect(os)}});var rr,fu,zf,Uv,Fv,mu,ai,li,ci,Bv,Kf,Jf,Yf=w(()=>{"use strict";rr=S(require("os")),fu=S(require("fs")),zf=S(require("child_process"));B();he();Uv="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",Fv={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},mu=rr.tmpdir(),ai=`${mu}/cloudflared`,li=null,ci=null,Bv=async()=>{if(await ge(ai))return;let e=Fv[rr.platform()+rr.arch()];if(!e)throw new Error(`tunnel on ${rr.platform()+rr.arch()} platform is not supported.`);let t=e.extract?mu+e.path:ai;await Je(`${Uv}/${e.path}`,t),e.extract&&await nt(t,mu),await fu.promises.chmod(ai,"755")},Kf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Pl(s.company.companyId,t),Bv()]);li=r._id,ci=zf.spawn(ai,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await kl(s.company.companyId,li),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await fu.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},Jf=async s=>{let e=[];return li&&e.push(_l(s.company.companyId,li)),ci&&e.push(new Promise((t,r)=>{ci.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ci.kill()})),await Promise.all(e)}});function zv(s,e){if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=`${e.width}x${e.height}`;return Kv(s,t)}function Kv(s,e){if(e){if(!Hv.includes(e)){vn.warn("Default resolution is used because the resolution is not supported by LT",{resolutionString:e,testResultId:s});return}return e}}function Xf(s,e){if(e){if(!qv.includes(e)){vn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var Qf,Zf,Gt,eg,tg,rg,ui,sg,vn,$v,Wv,wn,Vv,Gv,re,Hv,qv,pi=w(()=>{"use strict";Qf=S(require("ms")),Zf=S(require("p-retry")),Gt=S(require("os")),eg=S(require("portfinder")),tg=S(require("child_process"));B();Ge();he();rg=S(require("fs")),ui=S(require("fs/promises")),sg=require("path");J();$();Zo();ne();le();B();vn=C("lambdatestService"),$v="https://downloads.lambdatest.com/tunnel/v3",Wv={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"},wn=`${Gt.tmpdir()}/LT`,Vv=`${wn}/LT`,Gv=(0,Qf.default)("15m"),re=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.TESTIM_LAMBDATEST||e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){re.isLambdatestGrid(e)&&(re.lambdatestConfigPromise||=vl(),re.lambdatestConfig=await re.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Gv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(Vv))return;let t=Wv[Gt.platform()+Gt.arch()];if(!t)throw new Error(`tunnel on ${Gt.platform()+Gt.arch()} platform is not supported.`);let r=`${wn}.zip`;await Je(`${$v}/${t}`,r),await nt(r,wn)}static async chmodLtTunnel(e){if(!(Gt.platform()==="win32"||!await ge(e))){try{await ui.access(e,rg.constants.X_OK);return}catch{}try{await ui.chmod(e,"777")}catch(r){throw vn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ae(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){re.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await eg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;re.tunnelName=se();let c=["--tunnelName",re.tunnelName,"--infoAPIPort",String(t)];if(D.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],i&&a)c=[...c,"--ntlm-username",i,"--ntlm-password",a];else{let u=JSON.parse(D.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Oc(u)])}if(D.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)c=[...c,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await re.delay(3e3),await re.chmodLtTunnel((0,sg.join)(wn,"LT")),re.tunnel=tg.spawn("./LT",c,{cwd:wn});let d="",m="";re.tunnel.stdout.on("data",u=>{d+=u.toString()}),re.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,Zf.default)(()=>be(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});vn.info("LT tunnel info",u)}catch(u){throw vn.error("Failed to start LT tunnel",{err:u,stdoutResult:d,stderrResult:m}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!re.tunnel))return new Promise((t,r)=>{re.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),re.tunnel.kill()})}getCapabilities(e,t,r,n,o,i,a,l){var E,b;if(!this.isActive)return{};let c=re.lambdatestConfig.CAPABILITIES[t]||{},d={...re.tunnelName&&{tunnel:!0,tunnelName:re.tunnelName}},m=[],{canary:u,ext:f,extensionPath:g,installCustomExtension:h,headlessExtensionDownloadPath:y}=e,T={platform:Xf(n,a==null?void 0:a.os)||Xf(n,(E=i==null?void 0:i.lt)==null?void 0:E.platform)||c.platform||re.lambdatestConfig.PLATFORM,resolution:zv(n,a==null?void 0:a.resolution)||re.lambdatestConfig.RESOLUTION,version:t==="safari"&&((b=i==null?void 0:i.lt)==null?void 0:b.safari_version)||c.version};if(l===q.EXTENSION&&!f){let v=zl({canary:u,headlessExtensionDownloadPath:y},!0);!g&&v[t]&&(m=[...m,v[t]]),g&&ke(g)&&(m=[...m,g])}return h&&ke(h)&&(m=[...m,h]),{build:r,name:`${n} - ${o}`,selenium_version:re.lambdatestConfig.SELENIUM_VERSION,timezone:re.lambdatestConfig.TIMEZONE,...c,...T,loadExtension:m,...d,console:!0,queueTimeout:300,network:D.flags.LTNetworkCapabilities.isEnabled(),ntlm:D.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:D.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},Hv=["1024x768","1280x800","1280x1024","1366x768","1440x900","1680x1050","1600x1200","1920x1200","1920x1080","2048x1536","2560x1440"],qv=["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"]});var gu={};G(gu,{connect:()=>mi,disconnect:()=>fi,serveTunneling:()=>Yv});var di,ng,og,Jv,mi,fi,Yv,hu=w(()=>{"use strict";qf();fn();Yf();Qe();di=S(require("ora"));$();ne();pi();ng=C("tunnel"),og=s=>{var e;return[O.TESTIM_LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Jv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},mi=async s=>{if(!s.tunnel)return;let e=jt(),t;try{og(s)?(t=(0,di.default)("Starting testim lambdatest tunnel...").start(),await re.connectTunnel(s)):Jv(s)?(t=(0,di.default)("Starting testim cloudflare tunnel...").start(),await Kf(s)):(t=(0,di.default)("Starting testim ngrok tunnel...").start(),await Gf(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw ng.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},fi=async s=>{if(s.tunnel)try{og(s)?await re.disconnectTunnel(s):"tunnelRoutes"in s?await Jf(s):await Hf(s)}catch(e){let t="catch error - failed to close tunnel";throw ng.error(t,{err:e}),new Error(t)}},Yv=async(s,e=new Promise(()=>{}))=>(await mi(s),rs(()=>fi(s)),await e)});function Xv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.TESTIM_LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=ig.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function Qv(s){let e=ig.exec(s);return e==null?void 0:e[3]}function hi(s){var b,v,R,I,L,U,A,x,k,F,H;let e=s&&Qv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&Xv(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(b=s==null?void 0:s.hybrid)==null?void 0:b.tunnel,l=(v=s==null?void 0:s.external)==null?void 0:v.user,c=(R=s==null?void 0:s.external)==null?void 0:R.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&((U=(L=(I=s.hybrid)==null?void 0:I.external)==null?void 0:L[s.hybrid.tunnel])==null?void 0:U.user):l,u=d===O.HYBRID?a&&((k=(x=(A=s.hybrid)==null?void 0:A.external)==null?void 0:x[s.hybrid.tunnel])==null?void 0:k.key):c,f=s==null?void 0:s.name,g=s&&(s._id||s.gridId),h=s==null?void 0:s.provider,y=(F=s==null?void 0:s.mobileTokens)==null?void 0:F.androidToken,T=(H=s==null?void 0:s.mobileTokens)==null?void 0:H.iosToken,E=s==null?void 0:s.apiUrl;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:g,tunnel:a,user:l,key:c,type:d,name:f,provider:h,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:E}}async function cg(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Ze.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error(ht.UNKNOWN)}if(Ze.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Ze.error("invalid response - get grid",{res:o}),new Error(ht.UNKNOWN);if(o.status==="success"){let i=hi(o.grid);return Zv(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new ze(ht.NOT_FOUND):o.code==="no-available-slot"?new Yt(`Failed to run test on ${r} - concurrency limit reached`):(Ze.error("invalid code error response - get grid",{res:o}),new ze(ht.UNKNOWN))}function eS(s,e,t,r,n,o){return cg(t,e,s,n,()=>qo(e,t,r,n,o))}function tS(s,e,t,r,n,o,i){return cg(t,e,s,n,()=>{var c;let l=(c=i.allGrids)==null?void 0:c.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return l!=null&&l._id?qo(e,t,l._id,n,o):bl(e,t,r,n,o)})}function lg(s){return wl(s)}async function ug(s,e,t){let n=(t||await lg(s)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return hi(n)}async function rS(s,e,t){let n=(t||await lg(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return hi(n)}async function yu(s,e){let t=Sn[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete Sn[s],!r){Ze.warn("failed to find grid slot id",{projectId:e});return}Ze.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await hl(i,e,r,n,o)}catch(a){Ze.error("failed to release slot",{projectId:e,err:a})}}async function sS(s){let e=Object.values(Sn).filter(Boolean);if(e.length!==0){Ze.info("keep alive worker slots",{projectId:s,slots:e});try{await gl(s,e)}catch(t){Ze.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function nS(s){ag=global.setInterval(sS,1e4,s)}async function oS(s){let e=Object.keys(Sn);if(e.length){Ze.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>yu(Number(t),s))}catch(t){Ze.error("failed to release all slots",{err:t,projectId:s})}}}async function iS(s){await oS(s),clearInterval(ag)}function aS(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function cS(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function pg(s){let t=(()=>gi.isEmpty(s.testobjectSauce)?gi.isEmpty(s.saucelabs)?gi.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=aS(t,s),l=cS(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:l,key:a}}async function dg(s,e){let t=s.company.companyId;return await ug(t,e.gridId,s.allGrids)}async function mg(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:l}=s;if(n||i||o)return{mode:"local"};if(r)return pg(s);let c=t==null?void 0:t.companyId;if(a)return ug(c,a,e);if(l)return rS(c,l,e);if(Hs(s)||s.tunnelOnlyMode){Ze.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new ze("Missing host or grid configuration")}async function fg(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:l,useLocalChromeDriver:c,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(c||d||l)return{mode:"local"};if(n)return pg(t);if(a)return eS(r,u,o,a,s,e);if(i)return tS(r,u,o,i,s,e,t);throw new ze("Missing host or grid configuration")}var gi,Ze,Sn,ig,ag,Zv,En,gg,is=w(()=>{"use strict";gi=S(require("lodash"));he();$();B();ne();J();Ze=C("grid-service"),Sn={},ig=/(^(https?):\/{2})?(.*)/,ag=null;Zv=(s,e,t,r,n)=>{Sn[s]={gridId:t,companyId:e,slotId:r,browser:n}};En={start:nS,end:iS};gg=async(s={},e={},t={},r={},n={})=>{var g,h,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!i||!a||((a===O.TESTIM_LAMBDATEST||a===O.LAMBDATEST)&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e)),a!==O.HYBRID||!o||!l||!d||!m))return e;let u=await yl({companyId:o,gridId:i,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Ze.info("handling hybrid grid",{response:u,companyId:o});let f=hi({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((h=r.disable)==null||h.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});async function bu(s,e,t){let r=as[s];if(!r)return;let{slotId:n}=r;if(delete as[s],!n){at.warn("failed to find slot slot id",{companyId:e,workerId:s});return}at.info("release slot id",{companyId:e,slotId:n});try{await Ul(e,t,n)}catch(o){at.error("failed to release slot",{companyId:e,err:o})}}async function lS(s,e){let t=Object.values(as).filter(Boolean);if(t.length!==0){at.info("keep alive worker slots",{companyId:s,slots:t});try{await Bl(s,e,t)}catch(r){at.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function uS(s,e){hg=global.setInterval(()=>lS(s,e),1e4)}async function pS(s,e){let t=Object.keys(as);if(t.length){at.warn("not all slots released before end runner flow",{companyId:s});try{await ie(t,r=>bu(Number(r),s,e))}catch(r){at.error("failed to release all slots",{err:r,companyId:s})}}}async function dS(s,e){await pS(s,e),clearInterval(hg)}async function bg(s,e,t){let r;try{r=await Nl(s,e)}catch(n){throw at.error("failed to get slot",{companyId:s,err:n}),new Error(ht.UNKNOWN)}if(at.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw at.error("invalid response - get slot",{res:r}),new Error(ht.UNKNOWN);if(r.status==="success")return yg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new ze(ht.NOT_FOUND):r.code==="no-available-slot"?new Yt("Failed to run test - concurrency limit reached"):(at.error("invalid code error response - get slot",{res:r}),new ze(ht.UNKNOWN))}async function Tg(s,e,t,r){let n=as[r];if(!n)throw new Error("slot not found");Object.assign(n,t),yg(r,n),await Fl(s,e,n),at.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var at,as,hg,yg,Rn,cs=w(()=>{"use strict";he();$();B();ne();J();at=C("slot-service"),as={},hg=null,yg=(s,e)=>{as[s]=e};Rn={start:uS,end:dS}});function xn(){return yi||"master"}function wg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){yi="master";return}if(s!=null&&s.isArchived)throw new P(`Branch ${s.branch} is archived, run aborted.`);if(s){yi=s.branch||s;return}yi=e?"master":void 0}var yi,Tu=w(()=>{"use strict";J()});var Cn,wu,mS,vu,fS,bi,Ti,wi,vi,Si,Ei=w(()=>{"use strict";B();ne();Cn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===de.FAILED},wu=s=>{let{status:e}=s;return e===de.ABORTED},mS=s=>{let{status:e}=s;return e===de.PASSED},vu=s=>s.runnerStatus===Ac.SKIPPED,fS=s=>s.testStatus===Ye.EVALUATING,bi=(s,e)=>Object.values(s).filter(t=>{var r,n;return vu(t)&&(Xe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Ti=s=>Object.values(s).filter(e=>Cn(e)&&fS(e)).length,wi=s=>Object.values(s).filter(Cn),vi=s=>Object.values(s).filter(mS),Si=s=>Object.values(s).filter(wu)});function hS(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Su,Ii,gS,Ri,Sg=w(()=>{"use strict";Su=S(require("lodash"));$();Ei();Ii=C("debug-reporter"),gS=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],Ri=class{constructor(e){this.options=e}onTestStarted(e,t){Ii.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,o=r.host,i=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;Ii.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:o,failedGetBrowserAttempts:l,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Su.default.omit(this.options,gS),company:Su.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let l=hS(process.argv);Ii.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,o){let i=vi(e).length,a=Object.keys(e).length-i;Ii.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Eu,Pt,Pn=w(()=>{"use strict";ne();Eu=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===O.DEVICE_FARM}},Pt=new Eu});var Ru={};G(Ru,{Reporter:()=>yS});var sr,kn,Ir,Ai,Eg,Iu,yS,Au=w(()=>{"use strict";sr=S(require("chalk")),kn=S(require("lodash"));B();ne();Pn();Ei();Ir={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:Ai}=Ut,Eg="device",Iu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${sr.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?de.PASSED:de.FAILED,n=`(${e.testId})`,o=Ir[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${vo(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Ir.error("Failed runs are:")),console.log(Ir.error(t.join(`
|
|
22
|
-
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=wi(e),a=vi(e),l=Si(e),c=a.length,d=l.length,m=i.length,u="",f="";if(Pt.isTestStatusEnabled){let E=Ti(e);u=` FAILED-EVALUATING: ${E}`,m-=E,f=` SKIPPED: ${bi(e,this.options)}`}let g=this.buildTestPlanName(o,t),h,y=Ir[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${vo(r)}`;g.trim()===""||g.trim()==="Anonymous"?h=`Tests completed. ${T} (Execution ID: ${n})`:h=`Test plan${g} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=kn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=kn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=kn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=kn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let l=u=>{u.forEach((f,g)=>{var T;let h=(T=f.testData)!=null&&T.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",g+1,":",`${f.name}${Xe(f,this.options)?"-quarantine":""}`,y,h)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Ai.APPIUM?Eg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Ai.APPIUM?Eg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${sr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===Ai.APPIUM?"device":"browser";if(n)console.log(Ir.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(Ir.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===Ai.APPIUM?"Appium":"Selenium";console.log(Ir.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},yS=Iu});var Pu={};G(Pu,{Reporter:()=>ES});function bS(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function TS(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 wS(s){return`${s.visitedUrlsJson||""}`}async function vS(s,e,t,r,n,o){function i(u){let f=qe(s,t,u.testId,u.resultId,r),g={$:{name:bS(u),classname:n,time:Lc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(Cn(u)||wu(u)){let h=`Step Failed: ${u.failureReason||u.reason}`,y=Cn(u)?`${h} More info at: ${f}`:h;g.failure={$:{message:y}}}return vu(u)&&Xe(u,o)&&Pt.isTestStatusEnabled&&(g.skipped={}),o.urls&&(g["visited-urls-list"]=TS(u),g["visited-urls-json"]=wS(u)),g}function a(u){let{results:f,testPlanName:g,configName:h}=u,y=f||{},E={name:(h&&g?`${g} with config '${h}'`:g)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(Pt.isTestStatusEnabled){E.skipped=bi(y,o);let b=Ti(y);E.failures-=b,E["failure-evaluating"]=b}return{$:E,testcase:Object.keys(y).map(b=>i(y[b]))}}function l(u){let f=Object.keys(u).map(h=>u[h].startTime),g=Math.min.apply(null,f);return g?new Date(g).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return wi(u).length+Si(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Cu.Builder().buildObject(m)}catch(u){return SS(u)}}function SS(s){let e=new Cu.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 Cu,Ig,xu,ES,ku=w(()=>{"use strict";Cu=S(require("xml2js"));B();Ig=require("fs");Pn();Ei();xu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await vS(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Ig.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};ES=xu});var Rg={};G(Rg,{Reporter:()=>IS});function ls(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 _u,Ou,IS,Ag=w(()=>{"use strict";$();_u=C("team-city-reporter");Ou=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return ls(n)}onTestStarted(e,t,r,n){if(r){_u.debug("skip report test started because is rerun");return}let o=this.getPrintName(e);console.log(`##teamcity[testStarted name='${o}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,o,i){if(o){_u.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ls(t)}' details='${ls(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){_u.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ls(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ls(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ls(t)}']`)}},IS=Ou});var xg={};G(xg,{Reporter:()=>RS});var Lu,RS,Cg=w(()=>{"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,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},RS=Lu});var Pg={};G(Pg,{Reporter:()=>AS});var Du,AS,kg=w(()=>{"use strict";B();Xl();Du=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return ri(t)}},AS=Du});var Mu,ee,kt=w(()=>{"use strict";Sg();Mu=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 Ri(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Au(),Ru));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(ku(),Pu));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Ag(),Rg)),r.includes("console")&&Promise.resolve().then(()=>(Au(),Ru)),r.includes("junit")&&Promise.resolve().then(()=>(ku(),Pu)),r.includes("json")&&Promise.resolve().then(()=>(Cg(),xg)),r.includes("chrome")&&Promise.resolve().then(()=>(kg(),Pg))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,o){let i={};i=e;let a=Date.now()-(r||0);return[i,t,a,n,o]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var o;let n=t==null?void 0:t(...r);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||r))}}},ee=new Mu});function Og(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Lg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:g,gridType:h}){let y=Og({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:_g(c,d),isStartUp:u,projectType:f,gridType:h,...["android","ios"].includes(f)&&g&&{appSource:g}},m);bt("test-run-ci",y)}function Dg({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:g,projectType:h,appSource:y,gridType:T}){try{let E=Og({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:_g(d,m),isStartUp:g,projectType:h,gridType:T,...["android","ios"].includes(h)&&y&&{appSource:y}},u);if(n.success){bt("test-run-ci-success",E);return}bt("test-run-ci-fail",{...E,failureReason:n.failureReason})}catch(E){f.error("failed to update test end analytics",{err:E})}}function Mg(s){bt("batch-run-ci",s)}var _g,Nu=w(()=>{"use strict";ss();Go();_g=(s,e)=>s!=="cli"&&s!=="cli-local"?s:es&&e?"ci-with-user":es?"ci":e?"cli-with-user":s});var Ug,xi,Fg=w(()=>{"use strict";Ug=require("istanbul-lib-report"),xi=class extends Ug.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var Bg,jg,$g,_n,Tt,Wg,Ci,Uu,Vg,xS,Gg,Hg,CS,PS,qg,kS,_S,OS,LS,DS,zg,Kg=w(()=>{"use strict";Bg=S(require("ora")),jg=S(require("dayjs")),$g=S(require("test-exclude")),_n=S(require("fs")),Tt=S(require("path")),Wg=S(require("istanbul-reports")),Ci=S(require("istanbul-lib-report"));he();J();B();$();bn();Fg();Uu=C("test-run-status"),Vg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},xS=s=>!!Vg(s).search,Gg=s=>s?Vg(s).pathname.substring(1):"",Hg=(s,e)=>{let t=Gg(e);return!new $g.default({relativePath:!1,include:s}).shouldInstrument(t)},CS=s=>s.substring(0,s.indexOf("?")),PS=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await it("convert-source-map");if(t==="file"&&!e)throw new P("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},qg=(s,e)=>`${Tt.resolve(s,Gg(e))}.js`,kS=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ie(o.sources,async(i,a)=>{if(Hg(r,i))return;let l=qg(e,i);await _n.promises.mkdir(Tt.parse(l).dir,{recursive:!0}),await _n.promises.writeFile(l,o.sourcesContent[a])})})},_S={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(xS(e)&&(e=CS(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=Tt.dirname(this.getPath(s));return Tt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},OS=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=Ci.createContext({dir:t,coverageMap:e,watermarks:Ci.getDefaultWatermarks(),sourceFinder:a=>{try{let l=qg(r,a);return _n.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new xi({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:_S}),Wg.create(a,l).execute(i)}),o},LS=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await it("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Hg(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},DS=async(s,e)=>{let{mergeProcessCovs:r}=await it("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await El(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await un(l,9e4);await ie(c,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await ol(d.sourceUrl)),o.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},zg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Uu.info("start js coverage process");let n=(0,Bg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=Tt.resolve(s.codeCoverageReportPath||"./coverage"),i=Tt.resolve(o,`.js/${(0,jg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?Tt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([it("istanbul-lib-coverage"),DS(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Uu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ie(c.result,async({url:g,functions:h})=>{let{text:y,sourceMapType:T}=d.get(g),E=await PS({sourceMapType:T,source:y,sourceMapDir:a});u[g]=E;let b=await LS(s,{source:y,sourceMap:E,functions:h});m.merge(b)}),await kS(s,i,u);let f=await OS(s,m,o,i);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof P?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Uu.error(c,{err:l})}}});var Jg={};G(Jg,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Rr});var xe,MS,Rr,us=w(()=>{"use strict";B();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},MS=["ALL",...Object.values(xe)],Rr=class{constructor(){this.marks=Object.fromEntries(MS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,Io(r,50)],[`${t}_P95`,Io(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Zg={};G(Zg,{initServer:()=>FS,mapFilesToLocalDrive:()=>Bu});function Bu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Pi[t.id]?{screenshot:Pi[t.id]}:{})),Object.keys(ki).forEach(t=>{s.assets||={},s.assets[Qg[t]]=ki[t]}),s.assets||={},s.assets.screenshots=Object.values(Pi)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function FS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await it("multer"),n=typeof t=="string"?t:NS;await Fu.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=On.join(n,m.testResultId);try{await Fu.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=On.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,Xg.default)();i.post("/",o.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(Pi[d.stepId]=l.file.path),d.testResultId&&US.includes(d.subType)&&(ki[d.subType]||=[],ki[d.subType].push(l.file.path)),c.sendStatus(200)}),i.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new P(`Port ${s} is already in use`));default:return c(u)}}})}var Fu,Yg,On,Xg,NS,Pi,ki,Qg,US,ju=w(()=>{"use strict";Fu=S(require("fs")),Yg=S(require("os")),On=S(require("path")),Xg=S(require("express"));J();bn();NS=On.join(Yg.tmpdir(),"testim/rca/"),Pi={},ki={},Qg={"test-log":"consoleLogs","har-file":"networkLogs"},US=Object.keys(Qg)});var nr,$u,_i,eh=w(()=>{"use strict";nr=S(require("lodash"));B();$();$u=C("override-test-data-builder"),_i=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):$u.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):$u.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}$u.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return nr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),l=r[i],c=this.createNewTestItems(l,t);return r.splice(i,a-i+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=se();return{...e,resultId:o,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Oi(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw et.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Ar,et,BS,jS,$S,WS,Li,th=w(()=>{"use strict";Ar=S(require("lodash"));B();ne();is();cs();he();J();$();kt();fn();Kg();us();ju();pe();le();eh();Pn();et=C("test-run-status"),BS=hr(),jS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,$S=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,WS=ft();Li=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Rr;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Gs(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:lo||t.parallel||1,browser:o,gitBranch:BS,gitCommit:jS,gitRepoUrl:$S,runnerVersion:WS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:T,allLabels:E}=a,b={originalTestResultId:t,previousTestResultId:r,config:Ar.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:T,allLabels:E},xl({projectId:n,runId:o,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,ee.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:o,projectData:i}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Ko(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){et.error("failed to upload test data artifact (runner)",{err:d})}let l=Ar.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,vr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Xe(e,this.options))return;let n=this.exportsGlobal;try{let o=await Oi(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...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,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}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,n){let{name:o,testId:i,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Ye.EVALUATING&&Pt.isTestStatusEnabled){ee.onTestIgnored(e,r,`test in ${Ye.EVALUATING} status`);return}if(c){ee.onTestPassed(o);return}ee.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,i,l,this.branchToUse),i,n,l)}calcResultText(e){return e.success?de.PASSED:de.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);ee.onTestIgnored(e,r,`test in ${Ye.QUARANTINE}`)}monitorMemoryUsage(e){let t=Dc();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,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&Bu(i,et),i.resultUrl=qe(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o),this.monitorMemoryUsage(i),ee.onTestFinished(i,e,o);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await Oi(this.options.afterTest,{...e,exportsGlobal:o,globalParameters:o},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(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await vr(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw et.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=Pc;return e&&(n=o),Gr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,g,h;let l=e.browser?Ks(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Hr(D,n)&&qs(a.nativeApp)&&!e.appId,d=zs(e)&&(Gr(a.nativeApp,n)||c),m=Xe(a,e)||d,u={testId:a.testId,status:m?de.SKIPPED:de.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ye.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((g=a.testData)==null?void 0:g.total)||null,testDataIndex:((h=a.testData)==null?void 0:h.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(o)}async endKeepAlive(e,t,r){e==="redis"&&await Rn.end(r,t),e==="mongo"&&await En.end(t)}async executionStart(e,t,r,n,o){et.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=i;rs(()=>Promise.all([this.endKeepAlive(d,t,c),Ho("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...D.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},u=await Oi(i.beforeSuite,m),f=new _i(u,Ar.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:g}=this,h=[],y=[],T=[];for(let b of g){if(b.isBeforeTestPlan){h.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let E=async()=>{let b=Ar.cloneDeep(this.testRunStatus);await ie(Object.keys(b),async I=>{var k;let L=b[I],U=(k=L.config)==null?void 0:k.testData,A=L.testId,x=await Ko(t,A,I,U,l.defaults);x&&(delete L.config.testData,L.config.testDataUrl=x)});let v=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),R=ul({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:v,intersections:i.intersections});return this.executionStartedPromise=R,R.catch(I=>et.error(I)),R};try{await E()}catch(b){et.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:h,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Ar.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=Nc(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:u}of t)m===de.PASSED&&n++,m===de.SKIPPED&&o++,m===de.FAILED&&u===Ye.EVALUATING&&i++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Oi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}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 c=await zg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Ho("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw et.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await ll(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function GS(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 nh.readFileSync(s,{encoding:"base64"})}function lh(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&ke(s))&&s){let r=ch(s);ps.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Gu(r)} current extension count: ${e.length}`),e.push(r)}}function uh(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let c=typeof s.ext=="string"?s.ext:`${__dirname}/..`,d=r||c,m=`--load-extension=${d}`;ps.info(`adding extension: testim unpacked , path: ${d}`),t.push(m);return}let i=`testim-headless${s.canary?"-master.zip":".zip"}`;s.headlessExtensionDownloadPath&&(i=Di.basename(s.headlessExtensionDownloadPath));let a=Di.join(process.cwd(),i),l=ch(a);ps.info(`adding extension: testim zipped, path: ${a} length: ${l.length} hash: ${Gu(l)} current extension count: ${e.length}`),e.push(l)}function HS(s,e,t,r,n,o,i,a){var h,y;let l=t.seleniumName||t.browserValue,c=[],d=[...ah];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Wu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Wu.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},w3c:!0};Vu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Vu(n)&&l==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Wu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(h=e.projectData)==null?void 0:h.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+xc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),lh(r,c,i),a===q.EXTENSION&&uh(e,c,d,o,i),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],g={MicrosoftEdge:"ms",chrome:"goog"}[l];return re.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${g}:${f}`]=m),s}function zS(s,e,t){let r={"pdfjs.disabled":!0};return D.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":sh.join(","),"browser.helperApps.neverAsk.openFile":sh.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function KS(s){return`${s.width}x${s.height}`}function JS(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let o={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let i=(0,ih.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=KS(r.resolution||t.sl.screenResolution),delete i.screenResolution),ct.merge(i,o,n)}return ct.merge(o,n)}return{}}function YS(s,e,t){return ct.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function XS(s){return s.perfecto?s.perfecto:{}}function QS(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 ZS(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Ka(o,i)),a}function Mi(s){var E,b,v,R;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(o.mode==="local"){let I=[],L=[...ah],U={};return t.headless&&L.push("--headless"),t.silentDebuggerExtensionApi&&L.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&L.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(A=>L.push(`--${A}`)),t.chromeBinaryLocation&&(U.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&uh(t,I,L,null,c),lh(i,I,c),{logLevel:rh,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:L,extensions:I,...U},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=ZS(t,o),g={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:rh,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ct.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Vu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,g.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(g.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let h=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);ct.merge(g.desiredCapabilities,JS(t,r,n,e),YS(t,r,n),XS(t),QS(t,y,h),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((E=o.host)!=null&&E.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&D.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":g=qS(g,t,n,i,o,T,c,d);break;case"firefox":g=zS(g,t,c);break;case"safari":case"safari technology preview":g=GS(g,y);break;default:break}ct.merge(g.desiredCapabilities,t.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[D.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},L=k=>k[o.provider]||k[g.host]||k[I[g.host]],U=k=>{var F,H;return L(k)||k[(F=g.desiredCapabilities)==null?void 0:F.browserName]||k[(H=g.desiredCapabilities)==null?void 0:H.version]||k||{}},A=JSON.parse(D.flags.addCustomCapabilities.getValue()||"{}"),x=U(U(A));Object.keys(x).length&&(ps.info(`Adding custom capabilities: ${JSON.stringify(x)}`),Object.assign(g.desiredCapabilities,x))}catch(I){ps.error("Failed to load custom capabilities",{error:I,customCapabilities:D.flags.addCustomCapabilities.getValue()})}if(g.desiredCapabilities&&!g.capabilities&&(VS(g),g.capabilities={alwaysMatch:g.desiredCapabilities,firstMatch:[{}]},delete g.desiredCapabilities),g.hostname=g.host,s.printFinalCaps){let I=(b=g.capabilities)==null?void 0:b.alwaysMatch,L=JSON.parse(JSON.stringify(g)),U=(v=L==null?void 0:L.capabilities)==null?void 0:v.alwaysMatch,A=k=>k.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(k=>{var F,H;U!=null&&U[k]&&(U[k].extensions=(H=(F=I==null?void 0:I[k])==null?void 0:F.extensions)==null?void 0:H.map(A))}),U!=null&&U.loadExtension&&(U.loadExtension=(R=I==null?void 0:I.loadExtension)==null?void 0:R.map(A));let x=require("util");console.log(x.inspect(L,{showHidden:!1,depth:null,colors:!0}))}return g}var nh,Di,oh,ct,ih,ps,rh,Wu,ah,Gu,Vu,VS,qS,sh,Hu=w(()=>{"use strict";nh=S(require("fs")),Di=S(require("path")),oh=S(require("crypto")),ct=S(require("lodash"));B();pe();$();le();ne();pi();ih=require("lodash"),ps=C("testim-desired-capabilities-builder"),rh=co?"debug":"silent",Wu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},ah=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],Gu=(...s)=>oh.createHash("sha256").update(s.join("")).digest("hex"),Vu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",VS=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=D.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ps.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};qS=ct.memoize(HS,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(ct.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Gu(i,a,l,r,c,o)}),sh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Fe(s){var e,t,r,n,o,i,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function dh(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 qu=w(()=>{"use strict"});function zu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let g=u;g&&g!==u.ownerDocument;g=g.parentNode)if(f(g))return g;return null}function n(u,f){for(let g=u;g&&g!==u.ownerDocument;g=t(g))if(f(g))return g;return null}function o(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let h=window.getComputedStyle(u).getPropertyValue(f);if(h&&h!=="inherit")return h;let y=t(u);return o(y,f)}function i(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let h=o(u,"stroke-width");return!!h&&parseInt(h,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(u){return o(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!i(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,g=>g.tagName.toUpperCase()==="SELECT");return zu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(o(u,"opacity"))===0),m=!!n(s,u=>o(u,"display")==="none");return!(d||m||!i(s)||l(s))}var mh=w(()=>{"use strict"});var fh,gh,Ht,eE,tE,Ni,hh=w(()=>{"use strict";fh=S(require("promise-queue")),gh=S(require("webdriverio"));pe();$e();B();$();Ur();mh();qu();us();Ht=C("WebDriverApi"),eE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},tE={implicit:0,pageLoad:1,script:2},Ni=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Qa!==void 0&&(e=Qa);let t=1/0;this.queue=new fh.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,i;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),N("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t}),N("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await gh.remote(e),this.logGridStatus(r)}),N("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,xe.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let l of a.slots||[])if(((i=l==null?void 0:l.session)==null?void 0:i.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.info("grid status",{gridStatusMsg:o.message,ready:o.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("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},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){Ht.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Fe(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Fe(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(xe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Le(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(zu,{ELEMENT:e,[Kt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Fe(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(dh(e,this.isSafari(),Ht))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let o=[];return o[tE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Fe(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Le(e)),await this.elementIdValue(Le(e),t)}async getViewportSize(e){let t=await this.execute(eE);if(typeof e=="string"&&e.match(/(width|height)/)){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 o;return(o=this.client)==null?void 0:o.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Le(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var 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})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Fe(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Ht.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Ht.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var yh={};G(yh,{doubleClick:()=>rE});var rE,bh=w(()=>{"use strict";rE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(u){function f(E,b,v){return v>E&&v<b}let g=u.pointerPosition||{},h=r.getBoundingClientRect(),y=g.originX&&f(h.left,h.left+h.width,g.originX)?g.originX:h.left+h.width/2,T=g.originY&&f(h.top,h.top+h.height,g.originY)?g.originY:h.top+h.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,g){if(!window.PointerEvent)return;let h=a(f,g);return new window.PointerEvent(u,h)},c=function(u,f,g){let h=document.createEvent("MouseEvents");return h.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,g,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=i(u),g=u.event;return t.includes(g)?l(g,f.x,f.y):c(g,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Ln={};G(Ln,{dispatchFocus:()=>sE});function sE(s,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function r(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=r();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(s){let o=getLocatedElement(s);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Dn=w(()=>{"use strict"});var Eh={};G(Eh,{WebDriver:()=>Cr});async function aE(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 oE(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var ds,vh,Sh,Be,or,nE,Th,oE,ir,iE,wh,xr,Cr,Mn=w(()=>{"use strict";ds=S(require("lodash"));B();$e();Hu();vh=S(require("p-retry")),Sh=S(require("ua-parser-js"));Ur();$();qu();hh();J();le();us();Be=C("webdriver"),[or,nE]=[0,2],{extractElementId:Th,getCdpAddressForHost:oE}=Y,ir=()=>(Te(),Ne(tr)).getSessionPlayer().codeSnippets,iE=()=>(Te(),Ne(tr)).getSessionPlayer().locatorBuilderUtils,wh=()=>(Te(),Ne(tr)).getSessionPlayer().utils,xr=()=>(Te(),Ne(tr)).getSessionPlayer().positionUtils;Cr=class extends Ni{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,v,R,I,L,U,A,x;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:g,mode:h}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((R=(v=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:v.premiumFeatures)==null?void 0:R.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Mi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:g,mode:h});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,E=u?()=>null:()=>this.executeJS("window.focus()");try{N("before initClient in webdriver.js init");let k=await this.initClient(y,o,d);N("after initResult before getCdpAddress in init"),this.cdpUrl=await aE(k),N("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await ae(T),D.flags.dontFocusOnInit.isEnabled()||await E(),N("after focus and delay in webdriver.js init")}catch(k){let F=JSON.stringify(ds.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:k,capabilitiesAsString:F});let H=((L=(I=n==null?void 0:n.company)==null?void 0:I.activePlan)==null?void 0:L.plan)==="free";throw(U=k.stack)!=null&&U.includes("at startWebDriverSession")&&((A=k.message)!=null&&A.startsWith("Failed to create session"))&&((x=k.message)!=null&&x.includes("Timeout awaiting 'request'"))&&H?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):k.message.match(/Invalid username or password/)?new $r(k.message):k.message.match(/capabilit(y|ies)/)?new mo(k.message):k.message.match(/403 Forbidden/)?new Error("Grid Access Denied"):k.message.match(/Browser_Version not supported/)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${k.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>ds.zip(o.slice(0,-1),o.slice(1)),r=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(r).map(([o,i])=>i-o);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"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=se();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Be.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Be.warn("failed to click on alert",{err:l}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Th(r.value);return await this.switchToFrame({ELEMENT:n,[Kt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new fo:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||D.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
20
|
+
`))},ou=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:iu,argv:cu,exit:su,cwd:Ct}=global.process,Ev=["trace","debug","info","warn","error","silent"];_c(cu,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));au.description("Testim.io CLI").option("-h --help","output usage information",kf).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",De,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",De,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",De,[]).option("--test-id [test-id]","test ID to run",De,[]).option("-l, --label [label]","labels to search test by",De,[]).option("-n, --name [test-name]","test name to run",De,[]).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",wv).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",De,[]).option("--test-plan-id [test-plan-id]","test plan to run",De,[]).option("--suite [suite-name]","suite to run",De,[]).option("--suite-id [suite-id]","suite ID to run",De,[]).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",De,[]).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(iu.TESTIM_TEST_START_TIMEOUT)||2*60*1e3).option("--timeout [test-timeout]","Test run timeout in milliseconds",Number).option("--browser-timeout [open-browser-timeout]","Get browser from grid timeout in milliseconds",Number).option("--new-browser-wait-timeout [max-wait-to-browser]","Maximum get browser wait in minutes",Number).option("--get-browser-timeout [get-browser-timeout]","Timeout for a single attempt to get browser from the grid configured in the project's plan",Number).option("--get-browser-retries [get-browser-retries]","Number of attempts to get browser from the grid configured in the project's plan",Number).option("--get-session-timeout [get-session-timeout]",'Timeout for "/session" request to the selenium server',Number,(0,nu.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,nu.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: ${ou.join("/")}`,De,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",De,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",De,[]).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)",De,[]).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)",De,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").parse(cu);p=au.opts(),Iv=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},Rv=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Af=s=>{var r;if(!D.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=oi.readFileSync(s);(r=Kl)!=null&&r.containsEncryptedCredentials(t.toString())&&Kl.injectProxyCredentialsStoreToGlobal()},Av=async()=>{var T,E,b,v,I,x,L,F;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!cu.slice(2).length)throw kf(),new jr;if(p.version){let R="Testim CLI Version: ";iu.npm_package_version&&(console.log(R,iu.npm_package_version),su(0));let A=mt();A&&(console.log(R,A),su(0)),console.log("Could not find version, please check the package.json manually"),su(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&fm(),p.clearFileCache&&Yr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=Me.resolve(n);dm(R)}if(p.usePrefechedData&&gm(),p.playerRequirePath){let R=Me.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let A=Me.join(R,"tsconfig.node.json"),U=require("ts-node").register({project:A,ignore:[/node_modules/,new RegExp(`^${Vt.escapeRegExp(Me.relative(Ct(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:U.config.options.paths,baseUrl:U.config.options.baseUrl}),(Te(),Ne(tr)).options.playerPath=R;let Y=require("module"),X=Y.prototype.require;Y.prototype.require=function(tt){return tt==="rox-alias"?X.call(this,"rox-node"):tt==="canvas"?{}:X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=oi.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new P("missing --proxy option");if(ff(p))return gf(p);try{let R={};p.configFile?(Af(p.configFile),R=require(Me.join(Ct(),p.configFile)).config):p.optionsFile&&(R=require(Me.join(Ct(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(A=>{let k=Tv(A);p[k]=vv(p[k],R[A])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((T=p.testConfig)==null?void 0:T.length)||((E=p.testConfigId)==null?void 0:E.length),i=((b=p.testPlan)==null?void 0:b.length)||((v=p.testPlanId)==null?void 0:v.length),a=((I=p.suite)==null?void 0:I.length)||((x=p.suiteId)==null?void 0:x.length);if(p.seleniumCapsFile)try{r=require(Me.join(Ct(),p.seleniumCapsFile))}catch(R){throw new P(`Failed to parse selenium caps file file error: ${R.message}`)}if((L=p.reporters)!=null&&L.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Me.join(Ct(),p.chromeExtraPrefs))}catch(R){throw new P(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let A of R){let[k]=A.split("=");Rf.includes(k)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(A),k==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${k}), allowed values: ${JSON.stringify(Rf)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&Af(p.paramsFile),s={...s,...require(Me.join(Ct(),p.paramsFile))}}catch(R){throw new P(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new P(`Failed to parse params string error: ${R.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(Iv(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(Me.join(Ct(),p.sauceOptions)),A=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let U=R.browserName.toLowerCase();switch(U){case"microsoftedge":p.browser="edge";break;default:p.browser=U}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let k=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!A&&p.browser==="chrome"&&k)throw new P("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new P(`Failed to parse saucelabs options file error: ${R.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(Rv(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(Me.join(Ct(),p.browserstackOptions)),A=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(p.browser=R.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(R.browser_version)>=79&&(p.browser="edge-chromium"),!A&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new P(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(Me.join(Ct(),p.perfectoOptions)),A={location:"US East",securityToken:p.perfectoToken};p.perfecto={...A,...R}}catch(R){throw new P(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(Me.join(Ct(),p.testobjectOptions)),A={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...A,...R}}catch(R){throw new P(`Failed to parse test object options file error: ${R.message}`)}if(!p.project){let A=await(await Promise.resolve().then(()=>(ni(),ru))).getProjectId();if(A)p.project=A;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}D.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let A=await(await Promise.resolve().then(()=>(ni(),ru))).getToken();if(A)p.token=A;else throw new P("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let d=R=>R<=0||!Number.isInteger(R);if(d(p.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new P(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Sr,...yn].includes(p.browser))throw new P(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new P("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!Ev.includes(p.appiumLogLevel))throw new P(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new P("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(!i&&(p.beforeParallel!==1||p.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if((F=p.host)!=null&&F.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Cf.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(A=>A.trim()).filter(Boolean);let R=p.resultLabel.filter(A=>A.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&gr()&&p.resultLabel.unshift(gr()),R.length)throw new P("A result label cannot exceed 250 characters")}let u=cf(p),f=Qo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new P("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||i))throw new P("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!Vt.inRange(Vt.parseInt(p.setRetention),1,11))throw new P("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new P(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new P(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Vt.difference(p.codeCoverageReporter,ou).length){let R=Vt.difference(p.codeCoverageReporter,ou);throw new P(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let g={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(g).filter(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&y.length){let R=y.length>1?"are":"is";throw new P(`${y.map(A=>g[A]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=oi.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new P(`failed to parse field file error: ${R.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new P("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(Sv("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new P("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new P("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let R={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},A=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...A}}catch(R){throw new P(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
|
|
21
|
+
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?gr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionLocation:[p.extensionPath||u].flat(),extensionPath:p.extensionPath,headlessExtensionDownloadPath:p.headlessExtensionDownloadPath,playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var Nf={};H(Nf,{installAllLazyDependencies:()=>Pv,lazyRequire:()=>it});async function it(s,e={}){let t=Wc(s);if(t)return t;let r;e.silent||(r=(0,Lf.default)(`Installing ${s} before first usage...`).start());try{let n=await Cv(s);return r&&r.succeed(),n}catch(n){xv.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Mf(s),i=`${s}@${o}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${i}`;throw r&&r.fail(c),n}}async function Cv(s){return ns.has(s)||(ns.set(s,Df(s)),ns.get(s).catch(()=>{ns.delete(s)})),ns.get(s)}async function Df(s){let e=Wc(s);if(e)return e;let t=Mf(s),r=`${s}@${t}`;return await Do(ft(),r),Zt(s)}async function Pv(){let s=Object.keys(Xa);for(let e of s)await Df(e)}function Mf(s){let e=Object.entries(Xa).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Lf,xv,ns,bn=w(()=>{"use strict";Lf=S(require("ora"));Qr();$();B();io();Qs();xv=C("lazy-require"),ns=new Map});var Ff={};H(Ff,{preloadTests:()=>Tn});async function Tn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ht(async()=>{let t=await ie(s.testId,r=>al({...e,testId:r}),{concurrency:2});return Uf.keyBy(t,"testData.id")},"loadTests",kv,[e,s.testId])()}var Uf,kv,ii=w(()=>{"use strict";Uf=S(require("lodash"));Bt();he();B();kv=1e3*60*60*10});function lu(){return mt()}async function $f(){if(!_e)try{let s=await ce(Ov(),5e3,"The API call to NPM timed out"),e=lu();e&&jf.lt(e,s)&&console.log(Bf.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){_v.warn("Failed to get NPM version",{err:s})}}var Bf,jf,_v,Ov,uu=w(()=>{"use strict";Bf=S(require("chalk")),jf=S(require("semver"));B();pe();Qr();Bt();$();_v=C("npm-driver"),Ov=ht(()=>wm("@testim/testim-cli"),"getNpmVersion")});var pu,Dv,os,Wf,Vf,du,Gf,Hf=w(()=>{"use strict";B();K();$();bn();pu=C("testimNgrok"),Dv=".whitelisted-ngrok.testim.io",os="",Vf=async(s,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${se()}-${s.projectData.projectId}${Dv}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let o=await(await it("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(pu.info("replace https to http"),os=o.replace("https://","http://")):os=o,s.tunnelDiagnostics&&du(),s.baseUrl=os},du=async(s=!0)=>{try{let t=(await it("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===os);console.log("ngrok stats",n),pu.info("ngrok stats",{tunnel:n})}catch(e){pu.error("error collecting ngrok stats",{err:e})}s&&(Wf=setTimeout(()=>du(),1e4))},Gf=async s=>{if(!os)return;clearTimeout(Wf),s.tunnelDiagnostics&&await du(!1),await(await it("ngrok")).disconnect(os)}});var rr,fu,qf,Nv,Uv,mu,ai,li,ci,Fv,zf,Kf,Jf=w(()=>{"use strict";rr=S(require("os")),fu=S(require("fs")),qf=S(require("child_process"));B();he();Nv="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",Uv={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},mu=rr.tmpdir(),ai=`${mu}/cloudflared`,li=null,ci=null,Fv=async()=>{if(await ge(ai))return;let e=Uv[rr.platform()+rr.arch()];if(!e)throw new Error(`tunnel on ${rr.platform()+rr.arch()} platform is not supported.`);let t=e.extract?mu+e.path:ai;await Je(`${Nv}/${e.path}`,t),e.extract&&await nt(t,mu),await fu.promises.chmod(ai,"755")},zf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Pl(s.company.companyId,t),Fv()]);li=r._id,ci=qf.spawn(ai,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await kl(s.company.companyId,li),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await fu.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},Kf=async s=>{let e=[];return li&&e.push(_l(s.company.companyId,li)),ci&&e.push(new Promise((t,r)=>{ci.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ci.kill()})),await Promise.all(e)}});function qv(s,e){if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=`${e.width}x${e.height}`;return zv(s,t)}function zv(s,e){if(e){if(!Gv.includes(e)){vn.warn("Default resolution is used because the resolution is not supported by LT",{resolutionString:e,testResultId:s});return}return e}}function Yf(s,e){if(e){if(!Hv.includes(e)){vn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var Xf,Qf,Gt,Zf,eg,tg,ui,rg,vn,jv,$v,wn,Wv,Vv,re,Gv,Hv,pi=w(()=>{"use strict";Xf=S(require("ms")),Qf=S(require("p-retry")),Gt=S(require("os")),Zf=S(require("portfinder")),eg=S(require("child_process"));B();Ge();he();tg=S(require("fs")),ui=S(require("fs/promises")),rg=require("path");K();$();Zo();ne();le();B();vn=C("lambdatestService"),jv="https://downloads.lambdatest.com/tunnel/v3",$v={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"},wn=`${Gt.tmpdir()}/LT`,Wv=`${wn}/LT`,Vv=(0,Xf.default)("15m"),re=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.TESTIM_LAMBDATEST||e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){re.isLambdatestGrid(e)&&(re.lambdatestConfigPromise||=vl(),re.lambdatestConfig=await re.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Vv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(Wv))return;let t=$v[Gt.platform()+Gt.arch()];if(!t)throw new Error(`tunnel on ${Gt.platform()+Gt.arch()} platform is not supported.`);let r=`${wn}.zip`;await Je(`${jv}/${t}`,r),await nt(r,wn)}static async chmodLtTunnel(e){if(!(Gt.platform()==="win32"||!await ge(e))){try{await ui.access(e,tg.constants.X_OK);return}catch{}try{await ui.chmod(e,"777")}catch(r){throw vn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ae(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){re.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Zf.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;re.tunnelName=se();let c=["--tunnelName",re.tunnelName,"--infoAPIPort",String(t)];if(D.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],i&&a)c=[...c,"--ntlm-username",i,"--ntlm-password",a];else{let u=JSON.parse(D.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Oc(u)])}if(D.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)c=[...c,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await re.delay(3e3),await re.chmodLtTunnel((0,rg.join)(wn,"LT")),re.tunnel=eg.spawn("./LT",c,{cwd:wn});let d="",m="";re.tunnel.stdout.on("data",u=>{d+=u.toString()}),re.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,Qf.default)(()=>be(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});vn.info("LT tunnel info",u)}catch(u){throw vn.error("Failed to start LT tunnel",{err:u,stdoutResult:d,stderrResult:m}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!re.tunnel))return new Promise((t,r)=>{re.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),re.tunnel.kill()})}getCapabilities(e,t,r,n,o,i,a,l){var E,b;if(!this.isActive)return{};let c=re.lambdatestConfig.CAPABILITIES[t]||{},d={...re.tunnelName&&{tunnel:!0,tunnelName:re.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g,headlessExtensionDownloadPath:y}=e,T={platform:Yf(n,a==null?void 0:a.os)||Yf(n,(E=i==null?void 0:i.lt)==null?void 0:E.platform)||c.platform||re.lambdatestConfig.PLATFORM,resolution:qv(n,a==null?void 0:a.resolution)||re.lambdatestConfig.RESOLUTION,version:t==="safari"&&((b=i==null?void 0:i.lt)==null?void 0:b.safari_version)||c.version};if(l===q.EXTENSION&&!f){let v=zl({canary:u,headlessExtensionDownloadPath:y},!0);!h&&v[t]&&(m=[...m,v[t]]),h&&ke(h)&&(m=[...m,h])}return g&&ke(g)&&(m=[...m,g]),{build:r,name:`${n} - ${o}`,selenium_version:re.lambdatestConfig.SELENIUM_VERSION,timezone:re.lambdatestConfig.TIMEZONE,...c,...T,loadExtension:m,...d,console:!0,queueTimeout:300,network:D.flags.LTNetworkCapabilities.isEnabled(),ntlm:D.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:D.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},Gv=["1024x768","1280x800","1280x1024","1366x768","1440x900","1680x1050","1600x1200","1920x1200","1920x1080","2048x1536","2560x1440"],Hv=["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"]});var gu={};H(gu,{connect:()=>mi,disconnect:()=>fi,serveTunneling:()=>Jv});var di,sg,ng,Kv,mi,fi,Jv,hu=w(()=>{"use strict";Hf();fn();Jf();Qe();di=S(require("ora"));$();ne();pi();sg=C("tunnel"),ng=s=>{var e;return[O.TESTIM_LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Kv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},mi=async s=>{if(!s.tunnel)return;let e=jt(),t;try{ng(s)?(t=(0,di.default)("Starting testim lambdatest tunnel...").start(),await re.connectTunnel(s)):Kv(s)?(t=(0,di.default)("Starting testim cloudflare tunnel...").start(),await zf(s)):(t=(0,di.default)("Starting testim ngrok tunnel...").start(),await Vf(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw sg.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},fi=async s=>{if(s.tunnel)try{ng(s)?await re.disconnectTunnel(s):"tunnelRoutes"in s?await Kf(s):await Gf(s)}catch(e){let t="catch error - failed to close tunnel";throw sg.error(t,{err:e}),new Error(t)}},Jv=async(s,e=new Promise(()=>{}))=>(await mi(s),rs(()=>fi(s)),await e)});function Yv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.TESTIM_LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=og.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function Xv(s){let e=og.exec(s);return e==null?void 0:e[3]}function hi(s){var b,v,I,x,L,F,R,A,k,U,G;let e=s&&Xv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&Yv(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(b=s==null?void 0:s.hybrid)==null?void 0:b.tunnel,l=(v=s==null?void 0:s.external)==null?void 0:v.user,c=(I=s==null?void 0:s.external)==null?void 0:I.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&((F=(L=(x=s.hybrid)==null?void 0:x.external)==null?void 0:L[s.hybrid.tunnel])==null?void 0:F.user):l,u=d===O.HYBRID?a&&((k=(A=(R=s.hybrid)==null?void 0:R.external)==null?void 0:A[s.hybrid.tunnel])==null?void 0:k.key):c,f=s==null?void 0:s.name,h=s&&(s._id||s.gridId),g=s==null?void 0:s.provider,y=(U=s==null?void 0:s.mobileTokens)==null?void 0:U.androidToken,T=(G=s==null?void 0:s.mobileTokens)==null?void 0:G.iosToken,E=s==null?void 0:s.apiUrl;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:E}}async function ag(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Ze.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error(gt.UNKNOWN)}if(Ze.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Ze.error("invalid response - get grid",{res:o}),new Error(gt.UNKNOWN);if(o.status==="success"){let i=hi(o.grid);return Qv(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new ze(gt.NOT_FOUND):o.code==="no-available-slot"?new Yt(`Failed to run test on ${r} - concurrency limit reached`):(Ze.error("invalid code error response - get grid",{res:o}),new ze(gt.UNKNOWN))}function Zv(s,e,t,r,n,o){return ag(t,e,s,n,()=>qo(e,t,r,n,o))}function eS(s,e,t,r,n,o,i){return ag(t,e,s,n,()=>{var c;let l=(c=i.allGrids)==null?void 0:c.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return l!=null&&l._id?qo(e,t,l._id,n,o):bl(e,t,r,n,o)})}function cg(s){return wl(s)}async function lg(s,e,t){let n=(t||await cg(s)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return hi(n)}async function tS(s,e,t){let n=(t||await cg(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return hi(n)}async function yu(s,e){let t=Sn[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete Sn[s],!r){Ze.warn("failed to find grid slot id",{projectId:e});return}Ze.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await hl(i,e,r,n,o)}catch(a){Ze.error("failed to release slot",{projectId:e,err:a})}}async function rS(s){let e=Object.values(Sn).filter(Boolean);if(e.length!==0){Ze.info("keep alive worker slots",{projectId:s,slots:e});try{await gl(s,e)}catch(t){Ze.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function sS(s){ig=global.setInterval(rS,1e4,s)}async function nS(s){let e=Object.keys(Sn);if(e.length){Ze.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>yu(Number(t),s))}catch(t){Ze.error("failed to release all slots",{err:t,projectId:s})}}}async function oS(s){await nS(s),clearInterval(ig)}function iS(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function aS(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function ug(s){let t=(()=>gi.isEmpty(s.testobjectSauce)?gi.isEmpty(s.saucelabs)?gi.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=iS(t,s),l=aS(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:l,key:a}}async function pg(s,e){let t=s.company.companyId;return await lg(t,e.gridId,s.allGrids)}async function dg(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:l}=s;if(n||i||o)return{mode:"local"};if(r)return ug(s);let c=t==null?void 0:t.companyId;if(a)return lg(c,a,e);if(l)return tS(c,l,e);if(Hs(s)||s.tunnelOnlyMode){Ze.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new ze("Missing host or grid configuration")}async function mg(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:l,useLocalChromeDriver:c,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(c||d||l)return{mode:"local"};if(n)return ug(t);if(a)return Zv(r,u,o,a,s,e);if(i)return eS(r,u,o,i,s,e,t);throw new ze("Missing host or grid configuration")}var gi,Ze,Sn,og,ig,Qv,En,fg,is=w(()=>{"use strict";gi=S(require("lodash"));he();$();B();ne();K();Ze=C("grid-service"),Sn={},og=/(^(https?):\/{2})?(.*)/,ig=null;Qv=(s,e,t,r,n)=>{Sn[s]={gridId:t,companyId:e,slotId:r,browser:n}};En={start:sS,end:oS};fg=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!i||!a||((a===O.TESTIM_LAMBDATEST||a===O.LAMBDATEST)&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==O.HYBRID||!o||!l||!d||!m))return e;let u=await yl({companyId:o,gridId:i,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Ze.info("handling hybrid grid",{response:u,companyId:o});let f=hi({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((g=r.disable)==null||g.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});async function bu(s,e,t){let r=as[s];if(!r)return;let{slotId:n}=r;if(delete as[s],!n){at.warn("failed to find slot slot id",{companyId:e,workerId:s});return}at.info("release slot id",{companyId:e,slotId:n});try{await Ul(e,t,n)}catch(o){at.error("failed to release slot",{companyId:e,err:o})}}async function cS(s,e){let t=Object.values(as).filter(Boolean);if(t.length!==0){at.info("keep alive worker slots",{companyId:s,slots:t});try{await Bl(s,e,t)}catch(r){at.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function lS(s,e){gg=global.setInterval(()=>cS(s,e),1e4)}async function uS(s,e){let t=Object.keys(as);if(t.length){at.warn("not all slots released before end runner flow",{companyId:s});try{await ie(t,r=>bu(Number(r),s,e))}catch(r){at.error("failed to release all slots",{err:r,companyId:s})}}}async function pS(s,e){await uS(s,e),clearInterval(gg)}async function yg(s,e,t){let r;try{r=await Nl(s,e)}catch(n){throw at.error("failed to get slot",{companyId:s,err:n}),new Error(gt.UNKNOWN)}if(at.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw at.error("invalid response - get slot",{res:r}),new Error(gt.UNKNOWN);if(r.status==="success")return hg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new ze(gt.NOT_FOUND):r.code==="no-available-slot"?new Yt("Failed to run test - concurrency limit reached"):(at.error("invalid code error response - get slot",{res:r}),new ze(gt.UNKNOWN))}async function bg(s,e,t,r){let n=as[r];if(!n)throw new Error("slot not found");Object.assign(n,t),hg(r,n),await Fl(s,e,n),at.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var at,as,gg,hg,Rn,cs=w(()=>{"use strict";he();$();B();ne();K();at=C("slot-service"),as={},gg=null,hg=(s,e)=>{as[s]=e};Rn={start:lS,end:pS}});function xn(){return yi||"master"}function Tg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){yi="master";return}if(s!=null&&s.isArchived)throw new P(`Branch ${s.branch} is archived, run aborted.`);if(s){yi=s.branch||s;return}yi=e?"master":void 0}var yi,Tu=w(()=>{"use strict";K()});var Cn,wu,dS,vu,mS,bi,Ti,wi,vi,Si,Ei=w(()=>{"use strict";B();ne();Cn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===de.FAILED},wu=s=>{let{status:e}=s;return e===de.ABORTED},dS=s=>{let{status:e}=s;return e===de.PASSED},vu=s=>s.runnerStatus===Ac.SKIPPED,mS=s=>s.testStatus===Ye.EVALUATING,bi=(s,e)=>Object.values(s).filter(t=>{var r,n;return vu(t)&&(Xe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Ti=s=>Object.values(s).filter(e=>Cn(e)&&mS(e)).length,wi=s=>Object.values(s).filter(Cn),vi=s=>Object.values(s).filter(dS),Si=s=>Object.values(s).filter(wu)});function gS(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Su,Ii,fS,Ri,vg=w(()=>{"use strict";Su=S(require("lodash"));$();Ei();Ii=C("debug-reporter"),fS=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],Ri=class{constructor(e){this.options=e}onTestStarted(e,t){Ii.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,o=r.host,i=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;Ii.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:o,failedGetBrowserAttempts:l,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Su.default.omit(this.options,fS),company:Su.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let l=gS(process.argv);Ii.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,o){let i=vi(e).length,a=Object.keys(e).length-i;Ii.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Eu,Pt,Pn=w(()=>{"use strict";ne();Eu=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===O.DEVICE_FARM}},Pt=new Eu});var Ru={};H(Ru,{Reporter:()=>hS});var sr,kn,Er,Ai,Sg,Iu,hS,Au=w(()=>{"use strict";sr=S(require("chalk")),kn=S(require("lodash"));B();ne();Pn();Ei();Er={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:Ai}=Ut,Sg="device",Iu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${sr.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?de.PASSED:de.FAILED,n=`(${e.testId})`,o=Er[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${vo(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Er.error("Failed runs are:")),console.log(Er.error(t.join(`
|
|
22
|
+
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=wi(e),a=vi(e),l=Si(e),c=a.length,d=l.length,m=i.length,u="",f="";if(Pt.isTestStatusEnabled){let E=Ti(e);u=` FAILED-EVALUATING: ${E}`,m-=E,f=` SKIPPED: ${bi(e,this.options)}`}let h=this.buildTestPlanName(o,t),g,y=Er[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${vo(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=kn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=kn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=kn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=kn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let l=u=>{u.forEach((f,h)=>{var T;let g=(T=f.testData)!=null&&T.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",h+1,":",`${f.name}${Xe(f,this.options)?"-quarantine":""}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Ai.APPIUM?Sg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Ai.APPIUM?Sg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${sr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===Ai.APPIUM?"device":"browser";if(n)console.log(Er.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(Er.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===Ai.APPIUM?"Appium":"Selenium";console.log(Er.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},hS=Iu});var Pu={};H(Pu,{Reporter:()=>SS});function yS(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function bS(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 TS(s){return`${s.visitedUrlsJson||""}`}async function wS(s,e,t,r,n,o){function i(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:yS(u),classname:n,time:Lc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(Cn(u)||wu(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=Cn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return vu(u)&&Xe(u,o)&&Pt.isTestStatusEnabled&&(h.skipped={}),o.urls&&(h["visited-urls-list"]=bS(u),h["visited-urls-json"]=TS(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},E={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(Pt.isTestStatusEnabled){E.skipped=bi(y,o);let b=Ti(y);E.failures-=b,E["failure-evaluating"]=b}return{$:E,testcase:Object.keys(y).map(b=>i(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return wi(u).length+Si(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Cu.Builder().buildObject(m)}catch(u){return vS(u)}}function vS(s){let e=new Cu.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 Cu,Eg,xu,SS,ku=w(()=>{"use strict";Cu=S(require("xml2js"));B();Eg=require("fs");Pn();Ei();xu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await wS(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Eg.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};SS=xu});var Ig={};H(Ig,{Reporter:()=>ES});function ls(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 _u,Ou,ES,Rg=w(()=>{"use strict";$();_u=C("team-city-reporter");Ou=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return ls(n)}onTestStarted(e,t,r,n){if(r){_u.debug("skip report test started because is rerun");return}let o=this.getPrintName(e);console.log(`##teamcity[testStarted name='${o}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,o,i){if(o){_u.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ls(t)}' details='${ls(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){_u.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ls(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ls(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ls(t)}']`)}},ES=Ou});var Ag={};H(Ag,{Reporter:()=>IS});var Lu,IS,xg=w(()=>{"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,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},IS=Lu});var Cg={};H(Cg,{Reporter:()=>RS});var Du,RS,Pg=w(()=>{"use strict";B();Xl();Du=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return ri(t)}},RS=Du});var Mu,ee,kt=w(()=>{"use strict";vg();Mu=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 Ri(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Au(),Ru));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(ku(),Pu));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Rg(),Ig)),r.includes("console")&&Promise.resolve().then(()=>(Au(),Ru)),r.includes("junit")&&Promise.resolve().then(()=>(ku(),Pu)),r.includes("json")&&Promise.resolve().then(()=>(xg(),Ag)),r.includes("chrome")&&Promise.resolve().then(()=>(Pg(),Cg))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,o){let i={};i=e;let a=Date.now()-(r||0);return[i,t,a,n,o]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var o;let n=t==null?void 0:t(...r);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||r))}}},ee=new Mu});function _g(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Og({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=_g({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:kg(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);yt("test-run-ci",y)}function Lg({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let E=_g({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:kg(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){yt("test-run-ci-success",E);return}yt("test-run-ci-fail",{...E,failureReason:n.failureReason})}catch(E){f.error("failed to update test end analytics",{err:E})}}function Dg(s){yt("batch-run-ci",s)}var kg,Nu=w(()=>{"use strict";ss();Go();kg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:es&&e?"ci-with-user":es?"ci":e?"cli-with-user":s});var Ng,xi,Ug=w(()=>{"use strict";Ng=require("istanbul-lib-report"),xi=class extends Ng.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var Fg,Bg,jg,_n,bt,$g,Ci,Uu,Wg,AS,Vg,Gg,xS,CS,Hg,PS,kS,_S,OS,LS,qg,zg=w(()=>{"use strict";Fg=S(require("ora")),Bg=S(require("dayjs")),jg=S(require("test-exclude")),_n=S(require("fs")),bt=S(require("path")),$g=S(require("istanbul-reports")),Ci=S(require("istanbul-lib-report"));he();K();B();$();bn();Ug();Uu=C("test-run-status"),Wg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},AS=s=>!!Wg(s).search,Vg=s=>s?Wg(s).pathname.substring(1):"",Gg=(s,e)=>{let t=Vg(e);return!new jg.default({relativePath:!1,include:s}).shouldInstrument(t)},xS=s=>s.substring(0,s.indexOf("?")),CS=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await it("convert-source-map");if(t==="file"&&!e)throw new P("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Hg=(s,e)=>`${bt.resolve(s,Vg(e))}.js`,PS=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ie(o.sources,async(i,a)=>{if(Gg(r,i))return;let l=Hg(e,i);await _n.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await _n.promises.writeFile(l,o.sourcesContent[a])})})},kS={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(AS(e)&&(e=xS(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},_S=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=Ci.createContext({dir:t,coverageMap:e,watermarks:Ci.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Hg(r,a);return _n.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new xi({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:kS}),$g.create(a,l).execute(i)}),o},OS=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await it("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Gg(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},LS=async(s,e)=>{let{mergeProcessCovs:r}=await it("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await El(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await un(l,9e4);await ie(c,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await ol(d.sourceUrl)),o.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},qg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Uu.info("start js coverage process");let n=(0,Fg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=bt.resolve(s.codeCoverageReportPath||"./coverage"),i=bt.resolve(o,`.js/${(0,Bg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([it("istanbul-lib-coverage"),LS(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Uu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ie(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),E=await CS({sourceMapType:T,source:y,sourceMapDir:a});u[h]=E;let b=await OS(s,{source:y,sourceMap:E,functions:g});m.merge(b)}),await PS(s,i,u);let f=await _S(s,m,o,i);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof P?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Uu.error(c,{err:l})}}});var Kg={};H(Kg,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Ir});var xe,DS,Ir,us=w(()=>{"use strict";B();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},DS=["ALL",...Object.values(xe)],Ir=class{constructor(){this.marks=Object.fromEntries(DS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,Io(r,50)],[`${t}_P95`,Io(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Qg={};H(Qg,{initServer:()=>US,mapFilesToLocalDrive:()=>Bu});function Bu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Pi[t.id]?{screenshot:Pi[t.id]}:{})),Object.keys(ki).forEach(t=>{s.assets||={},s.assets[Xg[t]]=ki[t]}),s.assets||={},s.assets.screenshots=Object.values(Pi)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function US({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await it("multer"),n=typeof t=="string"?t:MS;await Fu.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=On.join(n,m.testResultId);try{await Fu.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=On.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,Yg.default)();i.post("/",o.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(Pi[d.stepId]=l.file.path),d.testResultId&&NS.includes(d.subType)&&(ki[d.subType]||=[],ki[d.subType].push(l.file.path)),c.sendStatus(200)}),i.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new P(`Port ${s} is already in use`));default:return c(u)}}})}var Fu,Jg,On,Yg,MS,Pi,ki,Xg,NS,ju=w(()=>{"use strict";Fu=S(require("fs")),Jg=S(require("os")),On=S(require("path")),Yg=S(require("express"));K();bn();MS=On.join(Jg.tmpdir(),"testim/rca/"),Pi={},ki={},Xg={"test-log":"consoleLogs","har-file":"networkLogs"},NS=Object.keys(Xg)});var nr,$u,_i,Zg=w(()=>{"use strict";nr=S(require("lodash"));B();$();$u=C("override-test-data-builder"),_i=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):$u.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):$u.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}$u.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return nr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),l=r[i],c=this.createNewTestItems(l,t);return r.splice(i,a-i+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=se();return{...e,resultId:o,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Oi(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw et.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Rr,et,FS,BS,jS,$S,Li,eh=w(()=>{"use strict";Rr=S(require("lodash"));B();ne();is();cs();he();K();$();kt();fn();zg();us();ju();pe();le();Zg();Pn();et=C("test-run-status"),FS=gr(),BS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,jS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,$S=mt();Li=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Ir;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Gs(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:lo||t.parallel||1,browser:o,gitBranch:FS,gitCommit:BS,gitRepoUrl:jS,runnerVersion:$S,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:E}=a,b={originalTestResultId:t,previousTestResultId:r,config:Rr.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:E},xl({projectId:n,runId:o,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,ee.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:o,projectData:i}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Ko(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){et.error("failed to upload test data artifact (runner)",{err:d})}let l=Rr.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,wr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Xe(e,this.options))return;let n=this.exportsGlobal;try{let o=await Oi(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...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,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}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,n){let{name:o,testId:i,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Ye.EVALUATING&&Pt.isTestStatusEnabled){ee.onTestIgnored(e,r,`test in ${Ye.EVALUATING} status`);return}if(c){ee.onTestPassed(o);return}ee.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,i,l,this.branchToUse),i,n,l)}calcResultText(e){return e.success?de.PASSED:de.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);ee.onTestIgnored(e,r,`test in ${Ye.QUARANTINE}`)}monitorMemoryUsage(e){let t=Dc();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,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&Bu(i,et),i.resultUrl=qe(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o),this.monitorMemoryUsage(i),ee.onTestFinished(i,e,o);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await Oi(this.options.afterTest,{...e,exportsGlobal:o,globalParameters:o},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(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await wr(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw et.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=Pc;return e&&(n=o),Gr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,h,g;let l=e.browser?Ks(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Hr(D,n)&&qs(a.nativeApp)&&!e.appId,d=zs(e)&&(Gr(a.nativeApp,n)||c),m=Xe(a,e)||d,u={testId:a.testId,status:m?de.SKIPPED:de.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ye.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(o)}async endKeepAlive(e,t,r){e==="redis"&&await Rn.end(r,t),e==="mongo"&&await En.end(t)}async executionStart(e,t,r,n,o){et.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=i;rs(()=>Promise.all([this.endKeepAlive(d,t,c),Ho("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...D.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},u=await Oi(i.beforeSuite,m),f=new _i(u,Rr.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let E=async()=>{let b=Rr.cloneDeep(this.testRunStatus);await ie(Object.keys(b),async x=>{var k;let L=b[x],F=(k=L.config)==null?void 0:k.testData,R=L.testId,A=await Ko(t,R,x,F,l.defaults);A&&(delete L.config.testData,L.config.testDataUrl=A)});let v=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),I=ul({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:v,intersections:i.intersections});return this.executionStartedPromise=I,I.catch(x=>et.error(x)),I};try{await E()}catch(b){et.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Rr.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=Nc(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:u}of t)m===de.PASSED&&n++,m===de.SKIPPED&&o++,m===de.FAILED&&u===Ye.EVALUATING&&i++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Oi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}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 c=await qg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Ho("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw et.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await ll(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function VS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function ah(s){return sh.readFileSync(s,{encoding:"base64"})}function ch(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&ke(s))&&s){let r=ah(s);ps.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Gu(r)} current extension count: ${e.length}`),e.push(r)}}function lh(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let o=s.headlessExtensionDownloadPath;if((s.ext||r)&&!o){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;ps.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;o&&(a=Di.basename(o));let l=Di.join(process.cwd(),a),c=ah(l);ps.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${Gu(c)} current extension count: ${e.length}`),e.push(c)}function GS(s,e,t,r,n,o,i,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...ih];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Wu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Wu.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},w3c:!0};Vu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Vu(n)&&l==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Wu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+xc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),ch(r,c,i),a===q.EXTENSION&&lh(e,c,d,o,i),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return re.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function qS(s,e,t){let r={"pdfjs.disabled":!0};return D.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":rh.join(","),"browser.helperApps.neverAsk.openFile":rh.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function zS(s){return`${s.width}x${s.height}`}function KS(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let o={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let i=(0,oh.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=zS(r.resolution||t.sl.screenResolution),delete i.screenResolution),ct.merge(i,o,n)}return ct.merge(o,n)}return{}}function JS(s,e,t){return ct.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function YS(s){return s.perfecto?s.perfecto:{}}function XS(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 QS(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Ka(o,i)),a}function Mi(s){var E,b,v,I;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(o.mode==="local"){let x=[],L=[...ih],F={};return t.headless&&L.push("--headless"),t.silentDebuggerExtensionApi&&L.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&L.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>L.push(`--${R}`)),t.chromeBinaryLocation&&(F.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&lh(t,x,L,null,c),ch(i,x,c),{logLevel:th,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:L,extensions:x,...F},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=QS(t,o),h={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:th,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ct.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Vu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);ct.merge(h.desiredCapabilities,KS(t,r,n,e),JS(t,r,n),YS(t),XS(t,y,g),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((E=o.host)!=null&&E.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&D.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=HS(h,t,n,i,o,T,c,d);break;case"firefox":h=qS(h,t,c);break;case"safari":case"safari technology preview":h=VS(h,y);break;default:break}ct.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let x={"hub.lambdatest.com":"lambdatest",[D.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},L=k=>k[o.provider]||k[h.host]||k[x[h.host]],F=k=>{var U,G;return L(k)||k[(U=h.desiredCapabilities)==null?void 0:U.browserName]||k[(G=h.desiredCapabilities)==null?void 0:G.version]||k||{}},R=JSON.parse(D.flags.addCustomCapabilities.getValue()||"{}"),A=F(F(R));Object.keys(A).length&&(ps.info(`Adding custom capabilities: ${JSON.stringify(A)}`),Object.assign(h.desiredCapabilities,A))}catch(x){ps.error("Failed to load custom capabilities",{error:x,customCapabilities:D.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(WS(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let x=(b=h.capabilities)==null?void 0:b.alwaysMatch,L=JSON.parse(JSON.stringify(h)),F=(v=L==null?void 0:L.capabilities)==null?void 0:v.alwaysMatch,R=k=>k.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(k=>{var U,G;F!=null&&F[k]&&(F[k].extensions=(G=(U=x==null?void 0:x[k])==null?void 0:U.extensions)==null?void 0:G.map(R))}),F!=null&&F.loadExtension&&(F.loadExtension=(I=x==null?void 0:x.loadExtension)==null?void 0:I.map(R));let A=require("util");console.log(A.inspect(L,{showHidden:!1,depth:null,colors:!0}))}return h}var sh,Di,nh,ct,oh,ps,th,Wu,ih,Gu,Vu,WS,HS,rh,Hu=w(()=>{"use strict";sh=S(require("fs")),Di=S(require("path")),nh=S(require("crypto")),ct=S(require("lodash"));B();pe();$();le();ne();pi();oh=require("lodash"),ps=C("testim-desired-capabilities-builder"),th=co?"debug":"silent",Wu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},ih=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],Gu=(...s)=>nh.createHash("sha256").update(s.join("")).digest("hex"),Vu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",WS=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=D.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ps.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};HS=ct.memoize(GS,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(ct.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Gu(i,a,l,r,c,o)}),rh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Fe(s){var e,t,r,n,o,i,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function ph(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 qu=w(()=>{"use strict"});function zu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function o(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return o(y,f)}function i(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=o(u,"stroke-width");return!!g&&parseInt(g,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?i(g):!1)}function a(u){return o(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!i(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return zu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(o(u,"opacity"))===0),m=!!n(s,u=>o(u,"display")==="none");return!(d||m||!i(s)||l(s))}var dh=w(()=>{"use strict"});var mh,fh,Ht,ZS,eE,Ni,gh=w(()=>{"use strict";mh=S(require("promise-queue")),fh=S(require("webdriverio"));pe();$e();B();$();Ur();dh();qu();us();Ht=C("WebDriverApi"),ZS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},eE={implicit:0,pageLoad:1,script:2},Ni=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Qa!==void 0&&(e=Qa);let t=1/0;this.queue=new mh.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,i;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),N("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t}),N("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await fh.remote(e),this.logGridStatus(r)}),N("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,xe.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let l of a.slots||[])if(((i=l==null?void 0:l.session)==null?void 0:i.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.info("grid status",{gridStatusMsg:o.message,ready:o.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("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},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){Ht.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Fe(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Fe(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(xe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Le(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(zu,{ELEMENT:e,[Kt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Fe(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(ph(e,this.isSafari(),Ht))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let o=[];return o[eE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Fe(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Le(e)),await this.elementIdValue(Le(e),t)}async getViewportSize(e){let t=await this.execute(ZS);if(typeof e=="string"&&e.match(/(width|height)/)){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 o;return(o=this.client)==null?void 0:o.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Le(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var 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})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Fe(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Ht.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Ht.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var hh={};H(hh,{doubleClick:()=>tE});var tE,yh=w(()=>{"use strict";tE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(u){function f(E,b,v){return v>E&&v<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=i(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Ln={};H(Ln,{dispatchFocus:()=>rE});function rE(s,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function r(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=r();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(s){let o=getLocatedElement(s);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Dn=w(()=>{"use strict"});var Sh={};H(Sh,{WebDriver:()=>xr});async function iE(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 nE(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var ds,wh,vh,Be,or,sE,bh,nE,ir,oE,Th,Ar,xr,Mn=w(()=>{"use strict";ds=S(require("lodash"));B();$e();Hu();wh=S(require("p-retry")),vh=S(require("ua-parser-js"));Ur();$();qu();gh();K();le();us();Be=C("webdriver"),[or,sE]=[0,2],{extractElementId:bh,getCdpAddressForHost:nE}=J,ir=()=>(Te(),Ne(tr)).getSessionPlayer().codeSnippets,oE=()=>(Te(),Ne(tr)).getSessionPlayer().locatorBuilderUtils,Th=()=>(Te(),Ne(tr)).getSessionPlayer().utils,Ar=()=>(Te(),Ne(tr)).getSessionPlayer().positionUtils;xr=class extends Ni{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,v,I,x,L,F,R,A;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((I=(v=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:v.premiumFeatures)==null?void 0:I.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Mi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,E=u?()=>null:()=>this.executeJS("window.focus()");try{N("before initClient in webdriver.js init");let k=await this.initClient(y,o,d);N("after initResult before getCdpAddress in init"),this.cdpUrl=await iE(k),N("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await ae(T),D.flags.dontFocusOnInit.isEnabled()||await E(),N("after focus and delay in webdriver.js init")}catch(k){let U=JSON.stringify(ds.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:k,capabilitiesAsString:U});let G=((L=(x=n==null?void 0:n.company)==null?void 0:x.activePlan)==null?void 0:L.plan)==="free";throw(F=k.stack)!=null&&F.includes("at startWebDriverSession")&&((R=k.message)!=null&&R.startsWith("Failed to create session"))&&((A=k.message)!=null&&A.includes("Timeout awaiting 'request'"))&&G?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):k.message.match(/Invalid username or password/)?new $r(k.message):k.message.match(/capabilit(y|ies)/)?new mo(k.message):k.message.match(/403 Forbidden/)?new Error("Grid Access Denied"):k.message.match(/Browser_Version not supported/)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${k.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>ds.zip(o.slice(0,-1),o.slice(1)),r=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(r).map(([o,i])=>i-o);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"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=se();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Be.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Be.warn("failed to click on alert",{err:l}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=bh(r.value);return await this.switchToFrame({ELEMENT:n,[Kt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new fo:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||D.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
23
23
|
var fn = ${ir().getLocatedElementCode};
|
|
24
24
|
return fn.apply(null, arguments);
|
|
25
25
|
`,t)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...n){return await this.timeouts("script",r),await this.executeAsync(t,...n)}async markDynamicParent(t,r){function n({attributeName:o,attributeValue:i,locatedElement:a}){let l=getLocatedElement(a);if(!l)throw new Error("could not find dynamic parent");l.setAttribute(o,i)}await this.executeJS(`
|
|
26
26
|
var getLocatedElement = ${ir().getLocatedElementCode};
|
|
27
27
|
var setDynamicParentAttribute = ${n.toString()};
|
|
28
28
|
return setDynamicParentAttribute.apply(null, arguments)
|
|
29
|
-
`,{attributeName:
|
|
29
|
+
`,{attributeName:oE().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(n){let o=getLocatedElement(n);if(!o)return null;let i=parseInt(window.getComputedStyle(o).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(o).paddingLeft.replace("px",""),10)||0,l=o.getBoundingClientRect();return{top:Math.round(l.top+i),left:Math.round(l.left+a)}}return this.executeJS(`
|
|
30
30
|
const getLocatedElement = ${ir().getLocatedElementCode};
|
|
31
31
|
const getLocation = ${r.toString()};
|
|
32
32
|
return getLocation.apply(null, arguments)
|
|
@@ -34,26 +34,26 @@ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they
|
|
|
34
34
|
const getLocatedElement = ${ir().getLocatedElementCode};
|
|
35
35
|
const getLocation = ${r.toString()};
|
|
36
36
|
return getLocation.apply(null, arguments)
|
|
37
|
-
`,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function r(o,i){function a(u){var
|
|
37
|
+
`,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function r(o,i){function a(u){var h;return(h=u.childNodes)!=null&&h.length&&Array.from(u.childNodes).filter(g=>g.nodeType===Node.ELEMENT_NODE).forEach(g=>{typeof g.tagName=="string"&&g.tagName.toLowerCase()==="title"?u.removeChild(g):a(g)}),u}function l(u){return["INPUT","TEXTAREA"].includes(u.tagName)}function c(u){var f,h,g;try{if(u.shadowRoot&&!((g=(h=Object.getOwnPropertyDescriptor((f=u.ownerDocument.defaultView)==null?void 0:f.Node.prototype,"textContent"))==null?void 0:h.get)!=null&&g.toString().includes("[native code]")))return u.shadowRoot.textContent.replace(/(\r\n|\n|\r)/gm,"")}catch{}if(i&&Array.prototype.some.call(u.children,y=>y.hidden)){let y=u.cloneNode(!0);return Array.prototype.filter.call(y.children,E=>E.hidden).forEach(E=>y.removeChild(E)),y.textContent.replace(/(\r\n|\n|\r)/gm,"")}return u.textContent.replace(/(\r\n|\n|\r)/gm,"")}function d(u){if(l(u))return u.value;if(u instanceof SVGElement){let f=u.cloneNode(!0);return a(f).textContent.replace(/(\r\n|\n|\r)/gm,"")}return c(u)}let m=getLocatedElement(o);return m?d(m):""}let{value:n}=await this.executeJS(`
|
|
38
38
|
const getLocatedElement = ${ir().getLocatedElementCode};
|
|
39
39
|
const extractText = ${r.toString()};
|
|
40
40
|
return extractText.apply(null, arguments)
|
|
41
|
-
`,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var o,i;let r=ir().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(xe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,xe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,xe.GET_HTML);let l=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(i=(o=this.client)==null?void 0:o.requestHandler)!=null&&i.sessionID||Object.assign(l,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),l}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class o extends Error{}function i(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,
|
|
41
|
+
`,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var o,i;let r=ir().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(xe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,xe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,xe.GET_HTML);let l=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(i=(o=this.client)==null?void 0:o.requestHandler)!=null&&i.sessionID||Object.assign(l,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),l}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class o extends Error{}function i(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,wh.default)(async()=>{let{value:c}=await this.windowHandleSize(),{value:d}=await this.execute(i),m=c.width-d.screenWidth,u=c.height-d.screenHeight;await this.windowHandleSize({width:t.width+m,height:t.height+u});let{value:f}=await this.execute(i);if(f.screenWidth!==t.width||f.screenHeight!==t.height)throw new o},{retries:5-1,factor:1,minTimeout:0}).catch(c=>{if(!(c instanceof o))throw c});if(typeof t!="object"||typeof t.width!="number"||typeof t.height!="number"||r!==void 0&&typeof r!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(r===void 0?!0:r)?a():this.windowHandleSize(t)}setViewportSize(t,r){return this.setViewportSizeNEW({width:t,height:r},!0)}getBrowserMajorVersion(t){try{return parseInt(t.browser.major,10)}catch(r){return Be.error("failed to get browser version",{err:r}),0}}async getBrowserAndOS(){function t(a){let l=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(l[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(l[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";l=l[2]?[l[1],l[2]]:[a.appName,a.appVersion,"-?"];let c=a.match(/version\/(\d+)/i);return c!==null&&l.splice(1,1,c[1]),l[0].toLowerCase()}if(this.browserAndOS)return this.browserAndOS;function r(){var a;return(a=window==null?void 0:window.navigator)!=null&&a.userAgent?window.navigator.userAgent:"unknown"}let{value:n}=await this.executeJS(r),o=(0,vh.default)(n),i=o.os;return this.browserAndOS={os:`${i.name} ${i.version}`,browserMajor:this.getBrowserMajorVersion(o),browser:t(n),userAgent:n,browserVersion:o.browser.version},this.browserAndOS}async getUserAgentInfo(){let{value:t}=await this.executeJS(`return ${ir().getUserAgentInfo()}`);return t}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:n,clickOffset:o}=t,i=Ar().calculateElementMiddlePoint(n),a=o.x,l=o.y;return!Th().isWithinBounds(n.left,n.left+n.width,i.x+a)||!Th().isWithinBounds(n.top,n.top+n.height,i.y+l)?(Be.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,l,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:n,clickOffset:o}=t,i=n.left+o.x+r.x,a=n.top+o.y+r.y;return{x:i,y:a}}async actWithActionsAPI(t,r,n,o){let i=this.getRelativeMoveActions(t,n),a=this.getClickActions(o,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:i.concat(a)}])}catch(l){Be.error("tried to use element origin but failed because of visibility, trying absolute",l);let{x:c,y:d}=this.computeAbsoluteMovement(t),m=this.getMoveActions(c,d);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:m.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,or,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(yh(),hh)),Promise.resolve().then(()=>(Dn(),Ln))]);return this.executeCodeAsync(`
|
|
42
42
|
var getLocatedElement = ${ir().getLocatedElementCode};
|
|
43
43
|
var dispatchFocus = ${n.toString()};
|
|
44
44
|
var doubleClick = ${r.toString()};
|
|
45
45
|
var eventData = arguments[0];
|
|
46
46
|
var done = arguments[1];
|
|
47
47
|
return doubleClick.call(null, eventData, done);
|
|
48
|
-
`,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,or,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,
|
|
49
|
-
var res = requireOrImportMethod('${
|
|
48
|
+
`,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,or,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,sE,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(Fe(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw n}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(n){if(Fe(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw n}}async dragAndDropOldAPI(t,r){return await this.moveTo(t),await this.buttonDown(),await this.moveTo(r),await this.buttonUp()}async calculateElementMiddlePoint(t,r={top:0,left:0}){let n=await this.getLocatedElementRect(t);if(!(n!=null&&n.value))throw Be.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:o,y:i,width:a,height:l}=n.value;return{x:r.left+o+a/2,y:r.top+i+l/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:o}=r.clickOffset;try{return await this.moveTo(t,n,o)}catch(i){if(Fe(i))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw i}}getMoveActions(t=1,r=1,n="viewport",o=0){return[{type:"pointerMove",duration:o,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){Be.error("tried to use element origin but failed because of visibility, trying location",n);let o=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(o)}}getDragCoordinates(t){let r=t.filter(i=>i.event==="mousemove"||i.event==="pointermove"),n=r[0].pointerPosition,o=r.at(-1).pointerPosition;return{xDiff:o.screenX-n.screenX,yDiff:o.screenY-n.screenY}}async dragWithMoveTo(t,r,n,o,i){return await this.moveTo(t,o,i),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,o,i){let a=this.getMoveActions(o,i,t,1),l=this.getClickActions(["pointerDown"],or),c=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],or);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(l).concat(c).concat(d)}])}async drag(t,r,n,o,i){let{width:a,height:l}=r,c=n-a/2+1,d=o-l/2,m=this.getDragCoordinates(i),{xDiff:u,yDiff:f}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,c,d);try{return await this.dragWithMoveTo(t,u,f,c,d)}catch(h){if(Fe(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,c,d);throw h}}getMoveRelativeSequence(t,r,n,o){let i=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},l={x:n,y:o},c=10,d=Math.round(i(a,l)/c),m=Array.from({length:d},()=>({x:Math.round((l.x-a.x)/d),y:Math.round((l.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,o){return this.getMoveRelativeSequence(t,r,n,o).reduce((a,l)=>{let c=a.at(-1);return a.concat({x:Math.round(c.x+l.x),y:Math.round(c.y+l.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:o,fromX:i,fromY:a,toRect:l,toX:c,toY:d}=n,m=Ar().calculateElementMiddlePoint(o),u=Ar().calculateElementMiddlePoint(l),f=this.getMoveRelativeSequence(m.x+i,m.y+a,u.x+c,u.y+d);await this.moveTo(t,Math.floor(i),Math.floor(a)),await this.buttonDown();for(let h of f)await this.moveTo(null,h.x,h.y);return await this.moveTo(r,Math.round(c),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:o,toRect:i,toX:a,toY:l}=t,c=Ar().calculateElementMiddlePoint(r),d=Ar().calculateElementMiddlePoint(i),m=Math.floor(c.x+n),u=Math.floor(c.y+o),f=Math.floor(d.x+a),h=Math.floor(d.y+l),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),T=this.getClickActions(["pointerDown"],or),E=ds.flatMap(g,x=>this.getMoveActions(x.x,x.y)),b=this.getMoveActions(f,h),v=this.getClickActions(["pointerUp"],or),I=y.concat(T).concat(E).concat(b).concat(v);return this.actions([{type:"pointer",id:"mouse",actions:I}])}async dragAndDrop(t,r,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,r,n)}catch(o){if(Fe(o))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw o}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(o){if(Fe(o))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw o}}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(o){if(Fe(o))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw o}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:o,toRect:i,toX:a,toY:l}=t,c=Ar().calculateElementMiddlePoint(r),d=Ar().calculateElementMiddlePoint(i),m=Math.floor(c.x+n),u=Math.floor(c.y+o),f=Math.floor(d.x+a),h=Math.floor(d.y+l);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],or);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],or);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(bh(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(o){Be.error("error getting element location",{err:o})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){Be.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Be.warn("failed to close session because session is undefined"),this.stopKeepAliveInterval();try{return await super.end()}catch{return}}async submit(t){if(this.unsupportedActions.has("submit"))return await super.submitFormManually(t);try{return await super.submitForm(t)}catch(r){if(Fe(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var Ku,Ju,Nn,Yu=w(()=>{"use strict";$();le();he();Ku=C("lab-features-service"),Ju=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(Ku.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await Sl(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){Ku.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=D.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:o}=this,i=n.find(l=>l.featureFlagName===e),a=i==null?void 0:i.enabled;return Boolean(o&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw Ku.error(t,{featureFlagName:e.name}),new Error(t)}},Nn=new Ju});function aE(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function cE(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:r}=globalThis.require("path"),{promises:n}=globalThis.require("fs");return{sync:!1,lib:n.readFile(`${s}${t}package.json`).then(i=>{let a=JSON.parse(i);return import(r(s,a.main||`${t}index.js`))})}}}function lE(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function uE(s,e,t,r,n={},o=void 0,i=void 0){let a=Object.keys(n).map(h=>`
|
|
49
|
+
var res = requireOrImportMethod('${aE(n[h])}');
|
|
50
50
|
if (res.sync) {
|
|
51
|
-
var ${
|
|
51
|
+
var ${h} = res.lib;
|
|
52
52
|
} else {
|
|
53
|
-
var ${
|
|
53
|
+
var ${h} = await res.lib;
|
|
54
54
|
}
|
|
55
55
|
`).join(""),l=i?`
|
|
56
|
-
${
|
|
56
|
+
${Rh.default.toString()}
|
|
57
57
|
var fileBuffer = dataUriToBuffer('${i}');
|
|
58
58
|
`:"var fileBuffer = null;",c=`
|
|
59
59
|
const getMessage = arguments => {
|
|
@@ -109,7 +109,7 @@ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they
|
|
|
109
109
|
});
|
|
110
110
|
`,d=`
|
|
111
111
|
function injectCode(params, args, incomingParams, context, code) {
|
|
112
|
-
const constructWithArguments = ${
|
|
112
|
+
const constructWithArguments = ${lE.toString()}
|
|
113
113
|
|
|
114
114
|
const resolve = result => {
|
|
115
115
|
parentPort.postMessage({
|
|
@@ -175,7 +175,7 @@ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they
|
|
|
175
175
|
// A hack to fix an issue with stringified functions which use require. when compiling to JS, calls to require change to __require.
|
|
176
176
|
const __require = require;
|
|
177
177
|
const { parentPort } = require('worker_threads');
|
|
178
|
-
const requireOrImportMethod = ${
|
|
178
|
+
const requireOrImportMethod = ${cE.toString()}
|
|
179
179
|
|
|
180
180
|
// requireCode will set async to be true if needed.
|
|
181
181
|
${a}
|
|
@@ -213,73 +213,73 @@ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they
|
|
|
213
213
|
injectCode(params, args, incomingParams, context, code);
|
|
214
214
|
});
|
|
215
215
|
})();
|
|
216
|
-
`,u=[],f=new
|
|
217
|
-
Action required: Please allow opening a websockets connection to ${fe} 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",()=>{Bi.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:Uh,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=`${fe}/${t}`,this._socket=ep.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Uh,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=`${fe}/${t}`,this._socket=ep.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(r[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Fh.default)(()=>ce(n(),IE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Bi.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Bh={};G(Bh,{remoteStepServiceSocketIO:()=>RE});var rp,RE,jh=w(()=>{"use strict";tp();rp=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},RE=new rp});var $h={};G($h,{remoteStepService:()=>bs});var sp,Fn,np,bs,ji=w(()=>{"use strict";Fi();ne();le();({REMOTE_STEP_SAVED:sp}=At),np=class{async init(e){D.flags.useNewWSCLI.isEnabled()||(Fn=(await Promise.resolve().then(()=>(jh(),Bh))).remoteStepServiceSocketIO,Fn.init(e))}joinToRemoteStep(e){return D.flags.useNewWSCLI.isEnabled()?wt.addFilter(`${e}:remoteStep`,{resultId:e},[sp]):Fn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(D.flags.useNewWSCLI.isEnabled()){wt.listenTo(`${e}:remoteStep`,[sp],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Fn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return D.flags.useNewWSCLI.isEnabled()?(wt.removeFilter(`${e}:remoteStep`,[sp]),Promise.resolve()):Fn.unlistenToRemoteStep(e)}},bs=new np});var op,kr,Wh=w(()=>{"use strict";tp();op=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=o=>{o.resultId===t&&o.testId===r&&n(o.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}},kr=new op});var Gh={};G(Gh,{testResultService:()=>_t});var Vh,ip,_t,$i=w(()=>{"use strict";Vh=require("events");Fi();ne();le();Wh();ip=class extends Vh.EventEmitter{init(e){if(D.flags.useNewWSCLI.isEnabled()){wt.onConnect=()=>this.emit("socket-connected");return}kr.init(e),kr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return D.flags.useNewWSCLI.isEnabled()?wt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]):kr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(D.flags.useNewWSCLI.isEnabled()){wt.removeFilter(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]);return}await kr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(D.flags.useNewWSCLI.isEnabled()){wt.listenTo(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}kr.listenToTestResult(e,t,r)}getSocket(){if(!D.flags.useNewWSCLI.isEnabled())return kr.getSocket()}},_t=new ip});var qh,zh,Kh,ve,AE,Jh,Hh,Wi,Yh=w(()=>{"use strict";qh=S(require("lodash"));B();pe();$e();ss();Qe();he();Mh();zh=S(require("p-retry")),Kh=require("url");$();ii();us();ne();ji();$i();ve=C("test-run-handler"),AE=3,Jh=20*1e3,Hh=s=>JSON.stringify(s).length<Jh,Wi=class{constructor(e,t,r,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Rr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?Ks(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,o,i,a;return this.isAppFromDevice?null:r?(o=(n=r.gridData)==null?void 0:n[e])==null?void 0:o[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(i=this._nativeApp.gridData)==null?void 0:i[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 qs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Gr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?To.FROM_DEVICE:To.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/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 getRunRequestParams(){var r,n;let t={tokenV3:await xt(),refreshToken:jo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:yd,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await $o()};if(this._options.disableMockNetwork&&bt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Hh(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,l=this.testId;i?(Object.assign(t,{runData:o}),ve.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):ve.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${Jh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await Tn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return ve.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 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 o;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Hh(e))return;let r=async()=>{try{return await Al(this._options.project,this._testId,this._testResultId,e)}catch(i){return ve.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Il(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?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)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){N("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&r.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{N("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=i||{};N("before Runtime.evaluate"),await(0,zh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),N("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return N("after Runtime.evaluate"),c.value}catch(i){throw ve.error("error running test using CDP",{err:i}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Kh.URL(e)}catch{return}let{username:n,password:o}=r;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=o=>{if(!r){if(this.isRetryKeyMismatch(o)){ve.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(o.reason)&&(ve.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),r=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await Sr(a,l,d,c);n(m),r||setTimeout(i,3e3)}catch(m){ve.error("failed to check if done",{err:m}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else _t.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await Sr(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return ve.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw ve.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}catch(o){throw ve.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await _t.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ve.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||_t.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){ve.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,r(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=qh.debounce(async()=>{try{let i=await Sr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(ve.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(i==null?void 0:i.status)==="completed"?(ve.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,r(i),!0):!1}catch(i){return ve.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)_t.on("socket-connected",async()=>{try{await _t.joinToTestResult(this._testResultId,this.testId)}catch(i){ve.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await fl(this._testResultId,this._options.project,this.retryKey);a?await e()||(ve.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){ve.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&_t.off("socket-connected",e)}}listenToRemoteStep(e){bs.listenToRemoteStep(this.testResultId,t=>{Dh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:AE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Vi,Xh=w(()=>{"use strict";Yh();Vi=class{constructor(e,t,r,n,o,i){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Wi(e,t,l,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var xE,CE,PE,Bn,ap=w(()=>{"use strict";is();cs();$();xE=C("worker-utils"),CE=async(s,e,t)=>{e&&await yu(s,t)},PE=async(s,e,t)=>{await bu(s,e,t)},Bn=async(s,e,t,r,n,o)=>{xE.info("releasing player",{hasPlayer:Boolean(o)});try{await(o==null?void 0:o.onDone())}finally{n==="mongo"&&await CE(s,e,t),n==="redis"&&await PE(s,r,t)}}});function DE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var up,ty,Hi,pp,ry,vt,Qh,Zh,cp,jn,kE,lp,_E,cr,OE,Gi,ey,LE,ME,Ot,$n=w(()=>{"use strict";up=S(require("ms")),ty=S(require("lodash")),Hi=S(require("p-retry")),pp=S(require("dayjs")),ry=S(require("dayjs/plugin/duration"));B();$e();is();cs();he();$();ap();kt();pi();le();ji();$i();Qe();Ge();ne();J();pp.default.extend(ry.default);vt=C("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Qh,TEST_START_TIMEOUT_MSG:Zh,TEST_COMPLETE_TIMEOUT_MSG:cp}=Ue,{SETUP_TIMEOUT:jn,NETWORK_ERROR:kE,GRID_ERROR:lp,BROWSER_CLOSED:_E,SELENIUM_ERROR:cr,UNKNOWN_ERROR:OE,MOBILE_SESSION_ERROR:Gi}=Vs,ey=(0,up.default)("600s"),LE=(0,up.default)("180s");ME=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,o,i,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.lambdatestService=new re;this.id=0;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await fg(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return ee.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Ns(!0)}async getBrowserOnce(e,t,r,n){throw new Ns(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),vt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Xe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,o;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Hr(D,(o=this.options.gridData)==null?void 0:o.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let i={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,i),i}}setSessionTimeout(){var e;if(this.options.mode===q.APPIUM){let t=(e=this.options.gridData)==null?void 0:e.type;return t===O.BROWSERSTACK?Math.max(ey,this.options.getSessionTimeout):D.flags.increaseTDCRequestTimeout.isEnabled()&&(t===O.TESTIM_TDC||t===O.TESTIM_HEADSPIN)?Math.max(ey,this.options.getSessionTimeout):Math.max(LE,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,Hi.default)(async()=>{let n=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(o){return t++,await this.handleGetSlotError(o,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Hi.default)(async()=>{var n,o;let r=Date.now();try{let i=(n=this.options.company)==null?void 0:n.companyId,a=(o=this.options.projectData)==null?void 0:o.projectId;return await ce(bg(i,a,this.id),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(i){return e++,await this.handleGetSlotError(i,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof Yt?vt.info("could not get grid slot due to concurrency issue",r):vt.error("error getting grid slot",{error:e,...r}),await ae(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 o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{N("before getSlotOnce retries");let{failedAttemptsCount:i,gridInfo:a={}}=await this.handleGetSlot(e);N("before getBrowserOnce retries");let l=this.options.getBrowserRetries-i;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,Hi.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await gg(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c;let f=this.setSessionTimeout();N("before getBrowserOnce");let g=await ce(this.getBrowserOnce(e,t,m,u),f,Ue.GET_BROWSER_TIMEOUT_MSG);return N("after getBrowserOnce"),ee.onGetBrowserSuccess(this.id,r),m||g}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},g=this.options.mode===q.APPIUM?"device":"browser";throw vt.error(`error getting ${g} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),ee.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof Et)&&this.options.mode!==q.APPIUM&&await ae(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),N("after getBrowserOnce retries")}catch(i){throw await Bn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Et,$r].some(a=>i instanceof a)?i:i instanceof ze?new fr(i,lp):new fr(i,cr)}return n}async runTest(e,t,r){var d;N("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=zs(this.options)&&this.handleMobileTest(e);if(i)return i;N("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await xt(),await this.runTestOnce(e,c)}finally{await Bn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,r,...n){var g,h;let o=async(y,T)=>{var F,H;if(Xe(y,this.options)||Hr(D,(F=this.options.gridData)==null?void 0:F.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id),r(...n);return}let E=e.sessionId,b=z=>T==null?void 0:T.message.includes(z),v=T&&T instanceof fr,R=T&&(b(Zh)||b(cp)),U=D.flags.retryOnSeleniumHubError.isEnabled()&&!!y.reason&&e.isSeleniumHubNoMatchSessionError(y.reason)&&!e.ignoreSeleniumHubError,A=R&&e.hasMoreTimeoutRetries(),x=e.hasMoreRetries()&&!v&&!R,k=!y.success&&(x||A||U);try{let z=e.retryKey;y.testRetryKey=z;let X=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,y,E,k,X),await this.runTestCleanup(),k){if(A&&await e.startNewTimeoutRetry(),U){vt.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:e.testId,retryReason:y.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let me=(H=this.options.projectData)==null?void 0:H.projectId,tt=e.testResultId,pt=e.testId;await zo(me,tt,pt,{show:!1}),e.decreaseSeleniumHubRetry(),e.decreaseRetryCount(),await e.startNewRetry()}return x&&!U&&!A&&await e.startNewRetry(),vt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:R,testRetryKey:z,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await f(k)}t(this.id),r(...n);return}catch(z){if(z instanceof Jt)return;vt.error("failed to process test result",{error:z}),t(this.id),r(...n);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
218
|
-
Please make sure the CLI has stable access to the internet. ${Ec()?"(Internal: network connectivity test failed)":""}`,
|
|
219
|
-
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(y.message)||/Couldn't connect to selenium server/.test(y.message)?{errorType:cr,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(y.message)?{errorType:cr,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(y.message)?{errorType:cr,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(y.message)?{errorType:cr,reason:`Session could not be created, please check that the ${E} you requested is supported in your plan`}:{errorType:OE,reason:b}},c=async y=>{var R;let T=await Sc();!T&&D.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),vt.warn("error on run",{err:y});let E=(R=this.userData)==null?void 0:R.projectId,{errorType:b,reason:v}=this.options.mode===q.APPIUM?a(y):l(y,T);zo(E,this.testResultId,this.testId,{status:Ws.COMPLETED,success:!1,reason:v,errorType:b,testRetryKey:e.retryKey,setupStepResult:{status:Ws.COMPLETED,success:!1,reason:v,errorType:b}},e.remoteRunId),await o(DE(this.testId,this.testName,this.testResultId,v),y)},d=async y=>{var R;let T=this.testId,E=this.testResultId,b=(R=this.userData)==null?void 0:R.projectId,v=this.branch;if(!T||!E||!b||!v)return vt.warn("Test failed. Not enough data to recover results via API",{err:y}),c(y);try{let I=await Sr(T,E,b,v);if(vt.warn("Test failed. Got results via API",{err:y,testResult:ty.default.omit(I,ME),resultId:E}),I&&I.status===Ws.COMPLETED&&!y.message.includes(cp))return await o(I);throw y}catch(I){return I!==y&&vt.error("Failed to fetch test results from server",{testId:T,resultId:E,projectId:b,branch:v,err:I}),c(y)}},m=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableResults)&&(this.options.useChromeLauncher||this.options.mode!==q.EXTENSION),u=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),f=async y=>{try{await Promise.all([!u&&bs.joinToRemoteStep(this.testResultId),!m&&_t.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==q.APPIUM&&e.validateRunConfig();let T=await this.runTest(e,this.customExtensionLocalLocation,y);await o(T),N("After onRunComplete"),t(this.id),r(...n)}catch(T){await d(T),t(this.id),r(...n)}finally{u||bs.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,f()}}});var dp,sy,Ts,mp=w(()=>{"use strict";B();dp=S(require("p-retry"));B();$();J();sy=C("window-utils"),Ts=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return sy.warn("selenium navigation failed. retrying to navigate",{err:o}),await ae(1500),r(n-1);throw!o.seleniumStack&&i&&sy.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([r(),ae(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ae(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,o=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ae(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 location<"u")r=location;else 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.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new Et("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,dp.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,dp.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var fp,ws,gp=w(()=>{"use strict";$();fp=C("cookies-utils"),ws=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw fp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw fp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw fp.error("failed to remove cookie",{err:t}),t}}}});var hp,qi,ny=w(()=>{"use strict";hp=S(require("p-retry")),qi=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[o,i]=await(0,hp.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,hp.default)(o,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}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 oy(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=s.offset||{top:0,left:0};if(o.top*=r,o.left*=r,!s.elementRect)return NE.warn("missing elementRect",ay.omit(s,"image")),{};let{elementRect:i}=s,a=await vs.default.read(Buffer.from(n[1],"base64")),l=i.left*r+o.left*r,c=i.top*r+o.top*r,d=i.width*r,m=i.height*r;l<0&&(d+=l,d=d<0?0:d,l=0),c<0&&(m+=c,m=m<0?0:m,c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new yp("height or width is equal or lower than zero");return{elementImage:await a.crop(l,c,d,m).getBase64Async(vs.default.MIME_PNG)}}async function UE(s,e){let t=await vs.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await vs.default.read(Buffer.from(o[1],"base64"));await new Promise((a,l)=>{t.composite(i,n.position.left,n.position.top,c=>{if(c){l(c);return}a()})})}return await t.getBase64Async(vs.default.MIME_PNG)}function FE(s,e){return UE(s,e)}async function BE(){}async function jE(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await BE(s[o]);return{key:o,url:i}}let r=await ie(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(o=>[o.key,o.url]));return Object.assign(s,n)}function iy(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 ay,vs,NE,yp,zi,cy=w(()=>{"use strict";ay=S(require("lodash"));B();vs=S(require("jimp"));$();NE=C("image-capture-utils"),yp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};zi=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 oy(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:iy(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 jE({screenImage:t.image,absoluteScreenHighlight:iy(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>ae(250),o=Boolean(e);async function i(u,f){o?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let g=await r.takeScreenshot(),h=await oy({elementRect:f},g);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:h.elementImage}}async function a(u){let f=[];for(let g of u){let h=await i(g.scrollPos,g.cropData);f.push(h)}return f}function l(u,f){let g=Math.max(u.width,f.width),h=f.width,y=Math.max(u.height,f.height),T=f.height,E=Array.from({length:Math.ceil(g/h)},(v,R)=>({scrollX:Math.min(R*h,g-h),cropX:R*h-Math.min(R*h,g-h),cropW:h-(R*h-Math.min(R*h,g-h))})),b=Array.from({length:Math.ceil(y/T)},(v,R)=>({scrollY:Math.min(R*T,y-T),cropY:R*T-Math.min(R*T,y-T),cropH:T-(R*T-Math.min(R*T,y-T))}));return E.flatMap(v=>b.map(R=>({scrollPos:{x:v.scrollX,y:R.scrollY},cropData:{top:R.cropY,left:v.cropX,width:v.cropW,height:R.cropH}})))}async function c(u,f){let g=await t.getCurrentScrollPosition(),h=l(u,f),y=await a(h);return await t.scrollToPosition(g),FE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var ly,uy,Ki,Ji,py=w(()=>{"use strict";ly=S(require("p-retry")),uy=S(require("semver"));B();$();mp();ny();cy();Te();Ki=C("tab-service"),Ji=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Ki.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,o={}){let i=await this.getTabDetails(t,e,o),a=se();function l(c){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!c.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:r,from:this.getTabInfo(e,i.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new Ts(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new zi(t,a,new qi(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(i=>r[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:o}=Z(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),l=n(i),c=n(a),d=r.map(m=>o.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Z();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(c=>o[c].url);if(this.exactUrlMatch(t,r,i))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,i,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){Ki.error("failed to get url or title",{err:o})}}catch(n){Ki.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ae(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(i=>r[i].openerStepId===t))return;if(this.pendingTabs[e]){Ki.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let o=await this.waitForTabToOpen(e);await this.addNewTab(e,o,this.pendingTabs[e]),this.addFrameHandler(o),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,ly.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=uy.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=Z();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let o=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,o),await this.tryToAddTab(e);let i=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,i);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var bp,Yi,Tp=w(()=>{"use strict";bp=class{select(){return console.log(`
|
|
216
|
+
`,u=[],f=new Ah.Worker(m,{eval:!0});try{return await ce(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};lt.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?lt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:i}):lt.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{lt.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o)}catch(h){if(!(h instanceof oe))throw h;return lt.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function pE(s){try{await Eh.promises.rm(s,{recursive:!0,force:!0})}catch(e){lt.warn("failed to remove install npm packages folder",{err:e})}}function xh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function fs(s,e,t,r,n,o){let i=xh(n,e,s,t),{data:a}=await dE(i,r,o);return a}async function gs(s,e,t,r,n,o,i,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||D.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=Em(y.testimPackageLocalLocation);return[y.paramName,ms.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=xh(i,n,e,o);if(c){let y=await un(c);y&&(l=y)}Buffer.isBuffer(l)&&(lt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let f="data:,";return l==="data:"&&(lt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=f),{...await uE(u,t,r,s,m,a,l),nodeVersion:process.version}}async function dE(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Ch(),i=D.flags.reuseCliPkgInstallFolder.isEnabled()?n:ms.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Im(i,r,a,t),lt.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=vm(i,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ms.resolve(i,"node_modules",m.packageName)}}),installFolder:i}}catch(d){throw lt.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await ce(l(),t)}catch(c){throw c instanceof oe&<.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Ch(){return ms.join(Ih.tmpdir(),"/testim_local_packages")}function mE(){let s=Ch();return pE(s)}var Eh,Ih,ms,Rh,Ah,lt,hs=w(()=>{"use strict";Eh=S(require("fs")),Ih=S(require("os")),ms=S(require("path"));B();Qr();Rh=S(require("data-uri-to-buffer")),Ah=require("worker_threads");K();$();he();Qr();le();lt=C("cli-service");mE().catch(s=>lt.warn("failed to clean local package folder",{err:s}))});var ar={};H(ar,{run:()=>gE});function fE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=D.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var gE,Ph=w(()=>{"use strict";hs();K();le();gE=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await gs(r,n,o,i,a,l,c,d,m,u);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 oe?new Error("Timeout while running action"):f}}});var Xu={};H(Xu,{run:()=>hE});var hE,kh=w(()=>{"use strict";hs();K();hE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await fs(t,r,n,i,o,a),success:!0}}catch(l){if(l instanceof It)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof oe)return{success:!1,code:"timeout"};throw l}}});async function Oh(s,e,t,r){try{return await Rl(s,e,t,r)}catch{Ui.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function bE(s,e,t,r,n){return Ui.info("finished to run remote step",{stepId:t,sessionId:n}),await Oh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function _h(s,e,t,r,n){return Ui.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Oh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Lh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o}=s,i=t.type,a=e.getSessionId(),l=t.id;Ui.info("start play remote step",{stepType:i,stepId:l,sessionId:a});let c=yE[i];if(!c)return await _h(n,r,l,`Failed to find step type ${i}`,a);try{let d=await c.run(e,t,o);return await bE(n,r,l,d,a)}catch(d){return await _h(n,r,l,d.message,a)}}var Ui,yE,Dh=w(()=>{"use strict";Ph();he();kh();$();Ui=C("step-playback"),yE={"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":ar,"cli-download-code-step":ar,"node-package":Xu}});var Qu,Mh,Cr,wE,Zu,Tt,Fi=w(()=>{"use strict";B();Qe();Qu=S(require("ws")),Mh=require("events");$();pe();Cr=C("socket-service"),wE=5e3,Zu=class extends Mh.EventEmitter{constructor(){super(...arguments);this.clientId=se();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Cr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),wE)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Cr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(ud);return xt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Qu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return Cr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{Cr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Qu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Cr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Cr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Cr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let o=i=>{r(i)&&(n(i),this.removeListener(t,o))};this.on(t,o)}listenTo(t,r,n,o){function i(l){n(l)&&o(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=i.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,o=!1){return new Promise(i=>{let a=se(),l={query:r,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",c=>c.id===a,i),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let o=this.listeners[`${t}:${n}`];o&&(delete this.listeners[`${t}:${n}`],o.forEach(i=>this.removeListener(n,i)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let o=Array.isArray(r)?r:[r];this.removeListeners(t,o),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},Tt=new Zu});var Uh,ep,vE,SE,EE,Nh,Bi,ys,tp=w(()=>{"use strict";Uh=S(require("p-retry")),ep=S(require("socket.io-client"));pe();B();$();vE=50,SE=10,EE=5e3,Nh=10*1e3,Bi=C("base socket service"),ys=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Bi.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Bi.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===SE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=vE)throw new Error(`Can't connect to Testim Servers.
|
|
217
|
+
Action required: Please allow opening a websockets connection to ${fe} 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",()=>{Bi.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:Nh,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=`${fe}/${t}`,this._socket=ep.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Nh,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=`${fe}/${t}`,this._socket=ep.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(r[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Uh.default)(()=>ce(n(),EE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Bi.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Fh={};H(Fh,{remoteStepServiceSocketIO:()=>IE});var rp,IE,Bh=w(()=>{"use strict";tp();rp=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},IE=new rp});var jh={};H(jh,{remoteStepService:()=>bs});var sp,Fn,np,bs,ji=w(()=>{"use strict";Fi();ne();le();({REMOTE_STEP_SAVED:sp}=At),np=class{async init(e){D.flags.useNewWSCLI.isEnabled()||(Fn=(await Promise.resolve().then(()=>(Bh(),Fh))).remoteStepServiceSocketIO,Fn.init(e))}joinToRemoteStep(e){return D.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:remoteStep`,{resultId:e},[sp]):Fn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(D.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:remoteStep`,[sp],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Fn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return D.flags.useNewWSCLI.isEnabled()?(Tt.removeFilter(`${e}:remoteStep`,[sp]),Promise.resolve()):Fn.unlistenToRemoteStep(e)}},bs=new np});var op,Pr,$h=w(()=>{"use strict";tp();op=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Pr=new op});var Vh={};H(Vh,{testResultService:()=>_t});var Wh,ip,_t,$i=w(()=>{"use strict";Wh=require("events");Fi();ne();le();$h();ip=class extends Wh.EventEmitter{init(e){if(D.flags.useNewWSCLI.isEnabled()){Tt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return D.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(D.flags.useNewWSCLI.isEnabled()){Tt.removeFilter(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(D.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!D.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},_t=new ip});var Hh,qh,zh,ve,RE,Kh,Gh,Wi,Jh=w(()=>{"use strict";Hh=S(require("lodash"));B();pe();$e();ss();Qe();he();Dh();qh=S(require("p-retry")),zh=require("url");$();ii();us();ne();ji();$i();ve=C("test-run-handler"),RE=3,Kh=20*1e3,Gh=s=>JSON.stringify(s).length<Kh,Wi=class{constructor(e,t,r,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Ir;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?Ks(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,o,i,a;return this.isAppFromDevice?null:r?(o=(n=r.gridData)==null?void 0:n[e])==null?void 0:o[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(i=this._nativeApp.gridData)==null?void 0:i[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 qs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Gr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?To.FROM_DEVICE:To.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/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 getRunRequestParams(){var r,n;let t={tokenV3:await xt(),refreshToken:jo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:hd,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await $o()};if(this._options.disableMockNetwork&&yt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Gh(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,l=this.testId;i?(Object.assign(t,{runData:o}),ve.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):ve.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${Kh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await Tn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return ve.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 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 o;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Gh(e))return;let r=async()=>{try{return await Al(this._options.project,this._testId,this._testResultId,e)}catch(i){return ve.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Il(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?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)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){N("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&r.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{N("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=i||{};N("before Runtime.evaluate"),await(0,qh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),N("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return N("after Runtime.evaluate"),c.value}catch(i){throw ve.error("error running test using CDP",{err:i}),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 zh.URL(e)}catch{return}let{username:n,password:o}=r;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=o=>{if(!r){if(this.isRetryKeyMismatch(o)){ve.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(o.reason)&&(ve.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),r=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await vr(a,l,d,c);n(m),r||setTimeout(i,3e3)}catch(m){ve.error("failed to check if done",{err:m}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else _t.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await vr(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return ve.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw ve.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}catch(o){throw ve.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await _t.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ve.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||_t.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){ve.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,r(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Hh.debounce(async()=>{try{let i=await vr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(ve.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(i==null?void 0:i.status)==="completed"?(ve.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,r(i),!0):!1}catch(i){return ve.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)_t.on("socket-connected",async()=>{try{await _t.joinToTestResult(this._testResultId,this.testId)}catch(i){ve.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await fl(this._testResultId,this._options.project,this.retryKey);a?await e()||(ve.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){ve.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&_t.off("socket-connected",e)}}listenToRemoteStep(e){bs.listenToRemoteStep(this.testResultId,t=>{Lh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:RE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Vi,Yh=w(()=>{"use strict";Jh();Vi=class{constructor(e,t,r,n,o,i){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Wi(e,t,l,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var AE,xE,CE,Bn,ap=w(()=>{"use strict";is();cs();$();AE=C("worker-utils"),xE=async(s,e,t)=>{e&&await yu(s,t)},CE=async(s,e,t)=>{await bu(s,e,t)},Bn=async(s,e,t,r,n,o)=>{AE.info("releasing player",{hasPlayer:Boolean(o)});try{await(o==null?void 0:o.onDone())}finally{n==="mongo"&&await xE(s,e,t),n==="redis"&&await CE(s,r,t)}}});function LE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var up,ey,Hi,pp,ty,wt,Xh,Qh,cp,jn,PE,lp,kE,cr,_E,Gi,Zh,OE,DE,Ot,$n=w(()=>{"use strict";up=S(require("ms")),ey=S(require("lodash")),Hi=S(require("p-retry")),pp=S(require("dayjs")),ty=S(require("dayjs/plugin/duration"));B();$e();is();cs();he();$();ap();kt();pi();le();ji();$i();Qe();Ge();ne();K();pp.default.extend(ty.default);wt=C("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Xh,TEST_START_TIMEOUT_MSG:Qh,TEST_COMPLETE_TIMEOUT_MSG:cp}=Ue,{SETUP_TIMEOUT:jn,NETWORK_ERROR:PE,GRID_ERROR:lp,BROWSER_CLOSED:kE,SELENIUM_ERROR:cr,UNKNOWN_ERROR:_E,MOBILE_SESSION_ERROR:Gi}=Vs,Zh=(0,up.default)("600s"),OE=(0,up.default)("180s");DE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,o,i,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.lambdatestService=new re;this.id=0;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await mg(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return ee.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Ns(!0)}async getBrowserOnce(e,t,r,n){throw new Ns(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Xe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,o;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Hr(D,(o=this.options.gridData)==null?void 0:o.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let i={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,i),i}}setSessionTimeout(){var e;if(this.options.mode===q.APPIUM){let t=(e=this.options.gridData)==null?void 0:e.type;return t===O.BROWSERSTACK?Math.max(Zh,this.options.getSessionTimeout):D.flags.increaseTDCRequestTimeout.isEnabled()&&(t===O.TESTIM_TDC||t===O.TESTIM_HEADSPIN)?Math.max(Zh,this.options.getSessionTimeout):Math.max(OE,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,Hi.default)(async()=>{let n=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(o){return t++,await this.handleGetSlotError(o,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Hi.default)(async()=>{var n,o;let r=Date.now();try{let i=(n=this.options.company)==null?void 0:n.companyId,a=(o=this.options.projectData)==null?void 0:o.projectId;return await ce(yg(i,a,this.id),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(i){return e++,await this.handleGetSlotError(i,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof Yt?wt.info("could not get grid slot due to concurrency issue",r):wt.error("error getting grid slot",{error:e,...r}),await ae(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 o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{N("before getSlotOnce retries");let{failedAttemptsCount:i,gridInfo:a={}}=await this.handleGetSlot(e);N("before getBrowserOnce retries");let l=this.options.getBrowserRetries-i;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,Hi.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await fg(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c;let f=this.setSessionTimeout();N("before getBrowserOnce");let h=await ce(this.getBrowserOnce(e,t,m,u),f,Ue.GET_BROWSER_TIMEOUT_MSG);return N("after getBrowserOnce"),ee.onGetBrowserSuccess(this.id,r),m||h}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw wt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),ee.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof Et)&&this.options.mode!==q.APPIUM&&await ae(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),N("after getBrowserOnce retries")}catch(i){throw await Bn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Et,$r].some(a=>i instanceof a)?i:i instanceof ze?new mr(i,lp):new mr(i,cr)}return n}async runTest(e,t,r){var d;N("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=zs(this.options)&&this.handleMobileTest(e);if(i)return i;N("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await xt(),await this.runTestOnce(e,c)}finally{await Bn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var k,U;if(Xe(g,this.options)||Hr(D,(k=this.options.gridData)==null?void 0:k.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId,E=G=>y==null?void 0:y.message.includes(G),b=y&&y instanceof mr,v=y&&(E(Qh)||E(cp)),L=D.flags.retryOnSeleniumHubError.isEnabled()&&!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)&&!e.ignoreSeleniumHubError,F=v&&e.hasMoreTimeoutRetries(),R=e.hasMoreRetries()&&!b&&!v,A=!g.success&&(R||F||L);try{let G=e.retryKey;g.testRetryKey=G;let Y=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,A,Y),await this.runTestCleanup(),A){if(F&&await e.startNewTimeoutRetry(),L){wt.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let X=(U=this.options.projectData)==null?void 0:U.projectId,me=e.testResultId,tt=e.testId;await zo(X,me,tt,{show:!1}),e.decreaseSeleniumHubRetry(),e.decreaseRetryCount(),await e.startNewRetry()}return R&&!L&&!F&&await e.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:G,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(A)}t(this.id,...r);return}catch(G){if(G instanceof Jt)return;wt.error("failed to process test result",{error:G}),t(this.id,...r);return}},o=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
218
|
+
Please make sure the CLI has stable access to the internet. ${Ec()?"(Internal: network connectivity test failed)":""}`,i=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:E,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:v}=kc,I=g instanceof Error?g.message:g;return I.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),I.includes(Xh)||I.includes(b)?{errorType:jn,reason:"timeout while getting device"}:I.includes(T)||I.includes(v)?{errorType:Gi,reason:"app doesn't exist on device"}:I.includes(E)?{errorType:Gi,reason:"app never started, check app permission or app activity"}:I.includes(y)?{errorType:Gi,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Gi,reason:I}},a=(g,y)=>{let T=this.options.mode===q.APPIUM?"device":"browser";if(!y&&D.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:PE,reason:o()};let E=g instanceof Error?g.message:g;if(E.includes(Xh))return{errorType:jn,reason:`Test couldn't get ${T}`};if(E.includes(Qh))return{errorType:jn,reason:"Test couldn't be started"};if(E.includes(cp)){if(!this.testRunTimeout)return{errorType:jn,reason:"Test timeout reached: test is too long"};let b=pp.default.duration({milliseconds:this.testRunTimeout}),v=Math.floor(b.asMinutes()),I=b.asSeconds(),x=v>0?` ${v} min`:"",L=I>0?` ${I} sec`:"";return{errorType:jn,reason:`Test timeout reached (timeout:${x}${L}): test is too long`}}if(g instanceof mr&&g.type){if(g.type===lp)return{errorType:lp,reason:`Test couldn't get ${T} from grid - ${g.message}`};if(g.type===cr)return{errorType:cr,reason:`Failed to create new session - ${g.message}`}}return"type"in g&&g.type===kE?{errorType:cr,reason:`Session terminated, this is often caused to connection
|
|
219
|
+
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:cr,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:cr,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:cr,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:cr,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:_E,reason:E}},l=async g=>{var v;let y=await Sc();!y&&D.flags.warnOnBadNetwork.isEnabled()&&console.warn(o()),wt.warn("error on run",{err:g});let T=(v=this.userData)==null?void 0:v.projectId,{errorType:E,reason:b}=this.options.mode===q.APPIUM?i(g):a(g,y);zo(T,this.testResultId,this.testId,{status:Ws.COMPLETED,success:!1,reason:b,errorType:E,testRetryKey:e.retryKey,setupStepResult:{status:Ws.COMPLETED,success:!1,reason:b,errorType:E}},e.remoteRunId),await n(LE(this.testId,this.testName,this.testResultId,b),g)},c=async g=>{var v;let y=this.testId,T=this.testResultId,E=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!T||!E||!b)return wt.warn("Test failed. Not enough data to recover results via API",{err:g}),l(g);try{let I=await vr(y,T,E,b);if(wt.warn("Test failed. Got results via API",{err:g,testResult:ey.default.omit(I,DE),resultId:T}),I&&I.status===Ws.COMPLETED&&!g.message.includes(cp))return await n(I);throw g}catch(I){return I!==g&&wt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:E,branch:b,err:I}),l(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===q.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&bs.joinToRemoteStep(this.testResultId),!d&&_t.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==q.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),N("After onRunComplete"),t(this.id,...r)}catch(y){await c(y),t(this.id,...r)}finally{m||bs.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,u()}}});var dp,ry,Ts,mp=w(()=>{"use strict";B();dp=S(require("p-retry"));B();$();K();ry=C("window-utils"),Ts=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return ry.warn("selenium navigation failed. retrying to navigate",{err:o}),await ae(1500),r(n-1);throw!o.seleniumStack&&i&&ry.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([r(),ae(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ae(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,o=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ae(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 location<"u")r=location;else 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.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new Et("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,dp.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,dp.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var fp,ws,gp=w(()=>{"use strict";$();fp=C("cookies-utils"),ws=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw fp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw fp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw fp.error("failed to remove cookie",{err:t}),t}}}});var hp,qi,sy=w(()=>{"use strict";hp=S(require("p-retry")),qi=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[o,i]=await(0,hp.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,hp.default)(o,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}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 ny(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=s.offset||{top:0,left:0};if(o.top*=r,o.left*=r,!s.elementRect)return ME.warn("missing elementRect",iy.omit(s,"image")),{};let{elementRect:i}=s,a=await vs.default.read(Buffer.from(n[1],"base64")),l=i.left*r+o.left*r,c=i.top*r+o.top*r,d=i.width*r,m=i.height*r;l<0&&(d+=l,d=d<0?0:d,l=0),c<0&&(m+=c,m=m<0?0:m,c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new yp("height or width is equal or lower than zero");return{elementImage:await a.crop(l,c,d,m).getBase64Async(vs.default.MIME_PNG)}}async function NE(s,e){let t=await vs.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await vs.default.read(Buffer.from(o[1],"base64"));await new Promise((a,l)=>{t.composite(i,n.position.left,n.position.top,c=>{if(c){l(c);return}a()})})}return await t.getBase64Async(vs.default.MIME_PNG)}function UE(s,e){return NE(s,e)}async function FE(){}async function BE(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await FE(s[o]);return{key:o,url:i}}let r=await ie(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(o=>[o.key,o.url]));return Object.assign(s,n)}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 iy,vs,ME,yp,zi,ay=w(()=>{"use strict";iy=S(require("lodash"));B();vs=S(require("jimp"));$();ME=C("image-capture-utils"),yp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};zi=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 ny(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 BE({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,n=()=>ae(250),o=Boolean(e);async function i(u,f){o?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await ny({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await i(h.scrollPos,h.cropData);f.push(g)}return f}function l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,E=Array.from({length:Math.ceil(h/g)},(v,I)=>({scrollX:Math.min(I*g,h-g),cropX:I*g-Math.min(I*g,h-g),cropW:g-(I*g-Math.min(I*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(v,I)=>({scrollY:Math.min(I*T,y-T),cropY:I*T-Math.min(I*T,y-T),cropH:T-(I*T-Math.min(I*T,y-T))}));return E.flatMap(v=>b.map(I=>({scrollPos:{x:v.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:v.cropX,width:v.cropW,height:I.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),UE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var cy,ly,Ki,Ji,uy=w(()=>{"use strict";cy=S(require("p-retry")),ly=S(require("semver"));B();$();mp();sy();ay();Te();Ki=C("tab-service"),Ji=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Ki.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,o={}){let i=await this.getTabDetails(t,e,o),a=se();function l(c){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!c.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:r,from:this.getTabInfo(e,i.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new Ts(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new zi(t,a,new qi(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(i=>r[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:o}=Z(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),l=n(i),c=n(a),d=r.map(m=>o.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Z();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(c=>o[c].url);if(this.exactUrlMatch(t,r,i))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,i,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){Ki.error("failed to get url or title",{err:o})}}catch(n){Ki.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ae(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(i=>r[i].openerStepId===t))return;if(this.pendingTabs[e]){Ki.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let o=await this.waitForTabToOpen(e);await this.addNewTab(e,o,this.pendingTabs[e]),this.addFrameHandler(o),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,cy.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=ly.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=Z();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let o=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,o),await this.tryToAddTab(e);let i=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,i);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var bp,Yi,Tp=w(()=>{"use strict";bp=class{select(){return console.log(`
|
|
220
220
|
internal error - cant use port selector in selenium!!!!
|
|
221
|
-
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Yi=new bp});var Wn,Xi,Qi=w(()=>{"use strict";gp();B();Te();Wn={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"},Xi=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Js;this.getLinksFromUnescapeHTML=Ys;this.cookieUtils=new ws(this.driver)}get sessionPlayerInit(){return Z()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,o=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-o.x,y:e.y-o.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function
|
|
221
|
+
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Yi=new bp});var Wn,Xi,Qi=w(()=>{"use strict";gp();B();Te();Wn={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"},Xi=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Js;this.getLinksFromUnescapeHTML=Ys;this.cookieUtils=new ws(this.driver)}get sessionPlayerInit(){return Z()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,o=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-o.x,y:e.y-o.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function dy(s){class e{constructor(r,n){this.frameManager=r;this.LocateElementPlayer=n;this._cache={}}cacheResults(r,n){this._cache[r]=n}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let n=py(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,o){let{frameOffset:i,locatedElement:a}=r,{locatorBuilderUtils:l}=Z();if(l.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw jE.error(u),new Error(u)}let c=await s.switchToLocatedFrame(a),d=py(c.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:i,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:o,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${o}`,seleniumFrameElement:c.value,frameLocateResultUrl:m}}async locate(r,n,o,i,a,l){let c=new this.LocateElementPlayer(i);r.targetId=`frameLocator_${n}`;let d=await c.locate(r,o,r.targetId);d.isVisible=!0;let m=await c.handleLocateResult(d,l,r).catch(()=>{throw new Error("")}),{locatedElement:u}=i.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:o.frameOffset.top+h.top,left:o.frameOffset.left+h.left},c.addFrameDataToContext&&c.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,o,i){let a=D.flags.enableFrameSwitchOptimization.isEnabled(),c=o.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=c&&c.stepId===r.id&&c.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),E=0;for(let b of T)E++,this.currentFrameHandler=await this.locate(b,E,this.currentFrameHandler,o,i,r);return this.currentFrameHandler}}let u=await i.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,o,i,r);return g}}return e}var jE,$E,py,my=w(()=>{"use strict";$();le();Te();Ur();jE=C("frame-locator"),$E="ELEMENT",py=s=>s?s[$E]||s[Kt]:null});var Zi,wp=w(()=>{"use strict";pe();Zi=()=>{try{if(ld)return!1;if(require("inspector").url())return!0}catch{}return!1}});var V,ue=w(()=>{"use strict";Te();V=class{constructor(e,t,r,n={},o=void 0,i=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=o;this.locateElementPlayer=i;this.exportsTest=a;this.frameId=0}get driver(){return this.stepActionUtils.driver}get sessionPlayerInit(){return Z()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(){try{return{success:!0,...await this.performAction()}}catch(e){let t=e==null?void 0:e.message,r=e==null?void 0:e.displayMessage;return{success:!1,reason:t,exception:e,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${t}`,error:r||t}}}}}});function VE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:D.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?D.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function GE(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t){let n=new fy.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,o,i,a){let{locatorBuilderUtils:l,codeSnippets:c,visibilityUtils:d,positionUtils:m}=Z();if(VE(n,d,m,s))return s.isVisible(e.seleniumElement);if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||l.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=c.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(I){throw kr.error("failed to execute getVisibilityCode",{err:I}),I}let{value:T}=y||{},E=T.elementVisibilityInfo||WE,[b,v]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(E,n,v,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=Z();await s.execute(r(t))}}}var fy,kr,WE,Vn,gy=w(()=>{"use strict";ue();$();le();Te();fy=require("linkedom"),kr=C("locate-step-action"),WE={opacity:1,clientRects:{}};Vn=class extends V{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return GE(e)}static getFrameIdByTestimFrameId(){throw kr.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw kr.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw kr.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw kr.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw kr.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw kr.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var hy={};H(hy,{scroll:()=>HE});var HE,yy=w(()=>{"use strict";HE=function(s,e,t,r,n,o,i,a){function l(E,b){if(!b)return{success:!1};elementScrollTo(b,E.x,E.y);let v=b.scrollLeft,I=b.scrollTop;return{success:Math.abs(I-E.y)<1&&Math.abs(v-E.x)<1,actualX:v,actualY:I}}function c(E,b){if(!t)return{x:n,y:o};let v=getLocatedElement(b);if(r&&!v)return{x:E.scrollWidth,y:E.scrollHeight};if(!v)throw new Error("could not find target element");let I=v.getBoundingClientRect(),x=0,L=0,F=Math.max(window.innerHeight-(I.height+10),0),R=Math.max(window.innerWidth-(I.width+10),0);return x=a?E.scrollTop+I.top-Math.min(o,F):E.scrollTop,L=i?E.scrollLeft+I.left-Math.min(n,R):E.scrollLeft,{x:Math.round(L),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 u={top:m.scrollTop,left:m.scrollLeft},f=c(m,e),h=l(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=c(m,e),h=l(f,m));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let E=T.getBoundingClientRect();g=E.left,y=E.top}return{success:h.success,actualX:g,actualY:y}}});var ea,by=w(()=>{"use strict";ue();ea=class extends V{getFailureString(e,t,r,n,o){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${o}, x: ${n})`;let i="Scrolling limit reached";return e.shouldScrollTop&&(i+=`. Expected top margin: ${r}, actual: ${o}`),e.shouldScrollLeft&&(i+=`. Expected left margin: ${t}, actual: ${n}`),i}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:o}}=this.sessionPlayerInit,i=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),l=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:c}=await Promise.resolve().then(()=>(yy(),hy)),d=`
|
|
222
222
|
const getLocatedElement = ${n.getLocatedElementCode};
|
|
223
223
|
const elementScrollTo = ${l.toString()};
|
|
224
224
|
const scroll = ${c.toString()};
|
|
225
225
|
return scroll.apply(null, arguments)
|
|
226
|
-
`;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:g}=m.value;return u?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,f,g)}}}catch{return{errorType:o.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 wy,vy=w(()=>{"use strict";wy=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,l){e[t(a)]=l},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),o=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,l){let c=document.createEvent("CustomEvent");c.initCustomEvent(l,!0,!0,null),Object.assign(c,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(c):a.fireEvent&&a.fireEvent(`on${l}`,c)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var Sy,Ey=w(()=>{"use strict";Sy=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(x){e({status:"done",result:x,success:!0})}function a(x){x||={},e({status:"failed",result:x,success:!1,keep:!0})}function l(x){return x!=null&&x.toLowerCase?(x=x.toLowerCase(),x==="text"?"text/plain":x==="url"?"text/uri-list":x):x}function c(){try{return new DataTransfer}catch{return{data:{},setData(k,F){o[l(k)]=F},getData(k){return o[l(k)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(x){let k=x;for(;k&&k!==document.documentElement;){if(k.draggable)return k;k=k.parentElement}return null}function g(x,k,F){let H=k.element,{dispatchDragEventsOnClosestDraggable:z}=F;if(d.includes(x.type)&&z){if(!H&&k.lastDraggedElement)return k.lastDraggedElement;let X=f(H);if(X)return k.lastDraggedElement=X,X}return H}function h(x,k,F){function H(pt,dr,_){return _>pt&&_<dr}let z=x.pointerPosition||{};if(k)return{x:z.originX||0,y:z.originY||0};let X=F.getBoundingClientRect(),me=z.originX&&H(X.left,X.left+X.width,z.originX)?z.originX:X.left+X.width/2,tt=z.originY&&H(X.top,X.top+X.height,z.originY)?z.originY:X.top+X.height/2;return{x:me,y:tt}}function y(x,k,F){let H=(k==null?void 0:k.modifiers)||{},z=h(x,F.isDrag,F.element),X=(k==null?void 0:k.button)||0,me=x.event;return m.includes(me)?E(me,H,z.x,z.y,X):u.includes(me)?v(me,H,z.x,z.y):b(me,H,z.x,z.y,X)}function T(x,k,F){return{screenX:0,screenY:0,clientX:k,clientY:F,ctrlKey:Boolean(x.ctrl),altKey:Boolean(x.alt),shiftKey:Boolean(x.shift),metaKey:Boolean(x.meta),bubbles:!0,cancelable:!0,composed:!0}}function E(x,k,F,H,z){if(n){let me=T(k,F,H);return me.pointerType="mouse",me.isPrimary=!0,new window.PointerEvent(x,me)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(x,!0,!0,document.defaultView,1,0,0,F,H,Boolean(k.ctrl),Boolean(k.alt),Boolean(k.shift),Boolean(k.meta),z,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function b(x,k,F,H,z){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(x,!0,!0,document.defaultView,1,0,0,F,H,Boolean(k.ctrl),Boolean(k.alt),Boolean(k.shift),Boolean(k.meta),z,document.body?document.body.parentNode:document.documentElement),X}function v(x,k,F,H){if(x==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let me=document.createEvent("CustomEvent");return me.initCustomEvent(x,!0,!0,null),Object.assign(me,{dataTransfer:window.TSTA.dataTransfer}),me}let z=T(k,F,H),X=new window.DragEvent(x,z);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function R(x,k,F){let H=g(x,k,F);H==null||H.dispatchEvent(x)}function I(x,k){function F(){return x.event==="click"&&k.isDrag&&!k.allEventsOnSameElement}return F()}function L(x,k,F){if(F){let H=Math.min(F.timeStamp-k.timeStamp,40);setTimeout(()=>{U(x)},H)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function U(x){let k,F=x.events[x.eventIndex],H=x.events[++x.eventIndex];try{x.element=getLocatedElement(F.locatedElement),k=y(F,s,x)}catch(z){return a(`exception in get event in drag step:${z.message}`)}if(I(F,x))return L(x,F,H);if(k)try{R(k,x,F)}catch(z){return a(`exception in executeEvent in drag step:${z.message}`)}else return a(`cannot execute event ${F.event}`);L(x,F,H)}let A={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{U(A)}catch(x){a(x)}},0)}});var Iy={};G(Iy,{doClick:()=>zE});var zE,Ry=w(()=>{"use strict";zE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(b,v){var L;function R(U){function A(){return o(U).find(F=>[...F.classList||[]].includes("Select-control"))}function x(){let F=A();return F?F.querySelector("input"):null}let k=x();k==null||k.focus()}let I=(L=b.quirks)==null?void 0:L.isReactSelect;v.type==="mousedown"&&I&&R(b.element)}function n(b,v){var I;let R=(I=b.quirks)==null?void 0:I.isCKEditorFrame;v.type==="click"&&R&&document.body.focus()}function o(b){let v=[];for(;b!=null&&b.parentNode;)v.push(b),b=b.parentNode;return v}function i(b){let v={status:"done",result:b,success:!0,...E.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},R=b.getBoundingClientRect(),I=R.left+R.width/2,L=R.top+R.height/2,x=f("mousemove",v,I,L,0);b.dispatchEvent(x)}function d(b,v){function R(x,k,F){return F>x&&F<k}let I=b.pointerPosition||{},L=v.getBoundingClientRect(),U=I.originX&&R(L.left,L.left+L.width,I.originX)?I.originX:L.left+L.width/2,A=I.originY&&R(L.top,L.top+L.height,I.originY)?I.originY:L.top+L.height/2;return{x:U,y:A}}function m(b,v,R){return{screenX:0,screenY:0,clientX:v,clientY:R,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,v,R,I){if(!window.PointerEvent)return;let L=m(v,R,I);return L.pointerType="mouse",L.isPrimary=!0,new window.PointerEvent(b,L)}function f(b,v,R,I,L){let U=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return U.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,R,I,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement),U}function g(b,v){let R=["pointerup","pointerdown","pointermove"],I=v.modifiers||{},L=d(b,v.element),U=v.button||0,A=b.event;return R.includes(A)?u(A,I,L.x,L.y):f(A,I,L.x,L.y,U)}function h(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return g(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),r(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let E={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!E.element){a("element not found");return}l(E.element),c(E.element);try{y(E);let b=h(),v=E.quirks,R=v==null?void 0:v.isReactSelect,I=v==null?void 0:v.isCKEditorFrame;!R&&!I&&dispatchFocus(s.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var Ay={};G(Ay,{doDragPath:()=>KE});var KE,xy=w(()=>{"use strict";KE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(b){e({status:"done",result:b,success:!0})}function i(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},R=b.getBoundingClientRect(),I=R.left+R.width/2,L=R.top+R.height/2,x=u("mousemove",v,I,L,0);b.dispatchEvent(x)}function c(b,v){function R(x,k,F){return F>x&&F<k}let I=b.pointerPosition||{};if(E.isDrag)return{x:I.originX||0,y:I.originY||0};let L=v.getBoundingClientRect(),U=I.originX&&R(L.left,L.left+L.width,I.originX)?I.originX:L.left+L.width/2,A=I.originY&&R(L.top,L.top+L.height,I.originY)?I.originY:L.top+L.height/2;return{x:U,y:A}}function d(b,v,R){return{screenX:0,screenY:0,clientX:v,clientY:R,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,v,R,I,L){if(r){let A=d(v,R,I);return A.pointerType="mouse",A.isPrimary=!0,new window.PointerEvent(b,A)}let U=document.createEvent("PointerEvent");return U.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,R,I,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),U}function u(b,v,R,I,L){let U=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return U.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,R,I,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement),U}function f(b,v){let R=["pointerup","pointerdown","pointermove"],I=v.modifiers||{},L=c(b,v.element),U=v.button||0,A=b.event;return R.includes(A)?m(A,I,L.x,L.y,U):u(A,I,L.x,L.y,U)}function g(b,v){function R(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return R()}function h(b,v,R){try{let I=f(v.events[b],v);g(I,v)||v.element.dispatchEvent(I)}catch{}if(b+1===v.events.length)R();else{let I=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{h(b+1,v,R)},I)}}function y(b,v){h(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let E={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(!E.element){i("element not found");return}a(E.element),l(E.element),y(E,()=>{o()})}});var Gn,ta,Cy=w(()=>{"use strict";Gn=S(require("lodash"));ue();vy();le();Ey();ta=class extends V{getDnDRectsAndOffsets(e,t,r,n){let o=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.x,fromY:o.y,toRect:t.rectWithoutFrameOffset,toX:i.x,toY:i.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return{success:!1,reason:"Malformed step: missing recorded events"};let i={isRoot:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Ry(),Iy)),Promise.resolve().then(()=>(Dn(),Ln))]),c=`
|
|
226
|
+
`;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,f,h)}}}catch{return{errorType:o.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 Ty,wy=w(()=>{"use strict";Ty=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,l){e[t(a)]=l},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),o=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,l){let c=document.createEvent("CustomEvent");c.initCustomEvent(l,!0,!0,null),Object.assign(c,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(c):a.fireEvent&&a.fireEvent(`on${l}`,c)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var vy,Sy=w(()=>{"use strict";vy=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(A){e({status:"done",result:A,success:!0})}function a(A){A||={},e({status:"failed",result:A,success:!1,keep:!0})}function l(A){return A!=null&&A.toLowerCase?(A=A.toLowerCase(),A==="text"?"text/plain":A==="url"?"text/uri-list":A):A}function c(){try{return new DataTransfer}catch{return{data:{},setData(k,U){o[l(k)]=U},getData(k){return o[l(k)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(A){let k=A;for(;k&&k!==document.documentElement;){if(k.draggable)return k;k=k.parentElement}return null}function h(A,k,U){let G=k.element,{dispatchDragEventsOnClosestDraggable:Y}=U;if(d.includes(A.type)&&Y){if(!G&&k.lastDraggedElement)return k.lastDraggedElement;let X=f(G);if(X)return k.lastDraggedElement=X,X}return G}function g(A,k,U){function G(St,Nr,_){return _>St&&_<Nr}let Y=A.pointerPosition||{};if(k)return{x:Y.originX||0,y:Y.originY||0};let X=U.getBoundingClientRect(),me=Y.originX&&G(X.left,X.left+X.width,Y.originX)?Y.originX:X.left+X.width/2,tt=Y.originY&&G(X.top,X.top+X.height,Y.originY)?Y.originY:X.top+X.height/2;return{x:me,y:tt}}function y(A,k,U){let G=(k==null?void 0:k.modifiers)||{},Y=g(A,U.isDrag,U.element),X=(k==null?void 0:k.button)||0,me=A.event;return m.includes(me)?E(me,G,Y.x,Y.y,X):u.includes(me)?v(me,G,Y.x,Y.y):b(me,G,Y.x,Y.y,X)}function T(A,k,U){return{screenX:0,screenY:0,clientX:k,clientY:U,ctrlKey:Boolean(A.ctrl),altKey:Boolean(A.alt),shiftKey:Boolean(A.shift),metaKey:Boolean(A.meta),bubbles:!0,cancelable:!0,composed:!0}}function E(A,k,U,G,Y){if(n){let me=T(k,U,G);return me.pointerType="mouse",me.isPrimary=!0,new window.PointerEvent(A,me)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(A,!0,!0,document.defaultView,1,0,0,U,G,Boolean(k.ctrl),Boolean(k.alt),Boolean(k.shift),Boolean(k.meta),Y,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function b(A,k,U,G,Y){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(A,!0,!0,document.defaultView,1,0,0,U,G,Boolean(k.ctrl),Boolean(k.alt),Boolean(k.shift),Boolean(k.meta),Y,document.body?document.body.parentNode:document.documentElement),X}function v(A,k,U,G){if(A==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let me=document.createEvent("CustomEvent");return me.initCustomEvent(A,!0,!0,null),Object.assign(me,{dataTransfer:window.TSTA.dataTransfer}),me}let Y=T(k,U,G),X=new window.DragEvent(A,Y);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function I(A,k,U){let G=h(A,k,U);G==null||G.dispatchEvent(A)}function x(A,k){function U(){return A.event==="click"&&k.isDrag&&!k.allEventsOnSameElement}return U()}function L(A,k,U){if(U){let G=Math.min(U.timeStamp-k.timeStamp,40);setTimeout(()=>{F(A)},G)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function F(A){let k,U=A.events[A.eventIndex],G=A.events[++A.eventIndex];try{A.element=getLocatedElement(U.locatedElement),k=y(U,s,A)}catch(Y){return a(`exception in get event in drag step:${Y.message}`)}if(x(U,A))return L(A,U,G);if(k)try{I(k,A,U)}catch(Y){return a(`exception in executeEvent in drag step:${Y.message}`)}else return a(`cannot execute event ${U.event}`);L(A,U,G)}let R={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{F(R)}catch(A){a(A)}},0)}});var Ey={};H(Ey,{doClick:()=>qE});var qE,Iy=w(()=>{"use strict";qE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(b,v){var L;function I(F){function R(){return o(F).find(U=>[...U.classList||[]].includes("Select-control"))}function A(){let U=R();return U?U.querySelector("input"):null}let k=A();k==null||k.focus()}let x=(L=b.quirks)==null?void 0:L.isReactSelect;v.type==="mousedown"&&x&&I(b.element)}function n(b,v){var x;let I=(x=b.quirks)==null?void 0:x.isCKEditorFrame;v.type==="click"&&I&&document.body.focus()}function o(b){let v=[];for(;b!=null&&b.parentNode;)v.push(b),b=b.parentNode;return v}function i(b){let v={status:"done",result:b,success:!0,...E.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},I=b.getBoundingClientRect(),x=I.left+I.width/2,L=I.top+I.height/2,A=f("mousemove",v,x,L,0);b.dispatchEvent(A)}function d(b,v){function I(A,k,U){return U>A&&U<k}let x=b.pointerPosition||{},L=v.getBoundingClientRect(),F=x.originX&&I(L.left,L.left+L.width,x.originX)?x.originX:L.left+L.width/2,R=x.originY&&I(L.top,L.top+L.height,x.originY)?x.originY:L.top+L.height/2;return{x:F,y:R}}function m(b,v,I){return{screenX:0,screenY:0,clientX:v,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,v,I,x){if(!window.PointerEvent)return;let L=m(v,I,x);return L.pointerType="mouse",L.isPrimary=!0,new window.PointerEvent(b,L)}function f(b,v,I,x,L){let F=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return F.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,x,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement),F}function h(b,v){let I=["pointerup","pointerdown","pointermove"],x=v.modifiers||{},L=d(b,v.element),F=v.button||0,R=b.event;return I.includes(R)?u(R,x,L.x,L.y):f(R,x,L.x,L.y,F)}function g(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return h(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),r(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let E={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!E.element){a("element not found");return}l(E.element),c(E.element);try{y(E);let b=g(),v=E.quirks,I=v==null?void 0:v.isReactSelect,x=v==null?void 0:v.isCKEditorFrame;!I&&!x&&dispatchFocus(s.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var Ry={};H(Ry,{doDragPath:()=>zE});var zE,Ay=w(()=>{"use strict";zE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(b){e({status:"done",result:b,success:!0})}function i(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},I=b.getBoundingClientRect(),x=I.left+I.width/2,L=I.top+I.height/2,A=u("mousemove",v,x,L,0);b.dispatchEvent(A)}function c(b,v){function I(A,k,U){return U>A&&U<k}let x=b.pointerPosition||{};if(E.isDrag)return{x:x.originX||0,y:x.originY||0};let L=v.getBoundingClientRect(),F=x.originX&&I(L.left,L.left+L.width,x.originX)?x.originX:L.left+L.width/2,R=x.originY&&I(L.top,L.top+L.height,x.originY)?x.originY:L.top+L.height/2;return{x:F,y:R}}function d(b,v,I){return{screenX:0,screenY:0,clientX:v,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,v,I,x,L){if(r){let R=d(v,I,x);return R.pointerType="mouse",R.isPrimary=!0,new window.PointerEvent(b,R)}let F=document.createEvent("PointerEvent");return F.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,I,x,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),F}function u(b,v,I,x,L){let F=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return F.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,x,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement),F}function f(b,v){let I=["pointerup","pointerdown","pointermove"],x=v.modifiers||{},L=c(b,v.element),F=v.button||0,R=b.event;return I.includes(R)?m(R,x,L.x,L.y,F):u(R,x,L.x,L.y,F)}function h(b,v){function I(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return I()}function g(b,v,I){try{let x=f(v.events[b],v);h(x,v)||v.element.dispatchEvent(x)}catch{}if(b+1===v.events.length)I();else{let x=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{g(b+1,v,I)},x)}}function y(b,v){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let E={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(!E.element){i("element not found");return}a(E.element),l(E.element),y(E,()=>{o()})}});var Gn,ta,xy=w(()=>{"use strict";Gn=S(require("lodash"));ue();wy();le();Sy();ta=class extends V{getDnDRectsAndOffsets(e,t,r,n){let o=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.x,fromY:o.y,toRect:t.rectWithoutFrameOffset,toX:i.x,toY:i.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return{success:!1,reason:"Malformed step: missing recorded events"};let i={isRoot:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Iy(),Ey)),Promise.resolve().then(()=>(Dn(),Ln))]),c=`
|
|
227
227
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
228
228
|
var dispatchFocus = ${l.toString()};
|
|
229
229
|
var doClick = ${a.toString()};
|
|
230
230
|
var eventData = arguments[0];
|
|
231
231
|
var done = arguments[1];
|
|
232
232
|
return doClick.call(null, eventData, done);
|
|
233
|
-
`;try{return(d=(await this.driver.executeCodeAsync(c,n,i)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var l;let e=(l=this.step.events[0])==null?void 0:l.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),o=this.isWithinBounds(r.top,r.top+r.height,e.originY),i=n?0:r.left+r.width/2-e.originX,a=o?0:r.top+r.height/2-e.originY;return{xOffset:i,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=Gn.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:n}=this.step,o=e.find(c=>["mousedown","pointerdown"].includes(c.event));if(o){let c=e.indexOf(o);e.splice(c,0,this.generateEventOfType(o,"mouseover"))}let{recordPointerMoveEvents:i=!1}=this.context.project.defaults||{},a=e.find(c=>c.event==="mouseup")||i&&e.find(c=>c.event==="pointerup"),l=Number(Gn.findLastIndex(e,c=>c.event==="mousemove")||i&&Gn.findLastIndex(e,c=>c.event==="pointermove"));a&&l>0&&!t&&e.splice(l+1,0,this.generateEventOfType(a,"mouseover")),r&&!n&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var d,m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3;if(!((d=e.events)!=null&&d.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let o=e.events,i={isRoot:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(
|
|
233
|
+
`;try{return(d=(await this.driver.executeCodeAsync(c,n,i)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var l;let e=(l=this.step.events[0])==null?void 0:l.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),o=this.isWithinBounds(r.top,r.top+r.height,e.originY),i=n?0:r.left+r.width/2-e.originX,a=o?0:r.top+r.height/2-e.originY;return{xOffset:i,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=Gn.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:n}=this.step,o=e.find(c=>["mousedown","pointerdown"].includes(c.event));if(o){let c=e.indexOf(o);e.splice(c,0,this.generateEventOfType(o,"mouseover"))}let{recordPointerMoveEvents:i=!1}=this.context.project.defaults||{},a=e.find(c=>c.event==="mouseup")||i&&e.find(c=>c.event==="pointerup"),l=Number(Gn.findLastIndex(e,c=>c.event==="mousemove")||i&&Gn.findLastIndex(e,c=>c.event==="pointermove"));a&&l>0&&!t&&e.splice(l+1,0,this.generateEventOfType(a,"mouseover")),r&&!n&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var d,m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3;if(!((d=e.events)!=null&&d.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let o=e.events,i={isRoot:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Ay(),Ry)),Promise.resolve().then(()=>(Dn(),Ln))]),c=`
|
|
234
234
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
235
235
|
var dispatchFocus = ${l.toString()};
|
|
236
236
|
var doDragPath = ${a.toString()};
|
|
237
237
|
return doDragPath.apply(null, arguments);
|
|
238
|
-
`;try{return(m=(await this.driver.executeCodeAsync(c,n,i)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset:n,rect:o}=e,i={frameOffset:{x:o.left-n.left,y:o.top-n.top},rect:n,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n)};if(D.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,i)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(D.flags.usePortedHtml5DragDrop.isEnabled()){let
|
|
238
|
+
`;try{return(m=(await this.driver.executeCodeAsync(c,n,i)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset:n,rect:o}=e,i={frameOffset:{x:o.left-n.left,y:o.top-n.top},rect:n,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n)};if(D.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,i)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(D.flags.usePortedHtml5DragDrop.isEnabled()){let h=this.generateHTML5DragEventSequence(),g=this.context.data.timeToPlayStep+3e3,y=this.getTarget(),T={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:h,eventData:{modifiers:this.step.modifiers,button:this.step.button},quirks:this.step.quirks,isDrag:this.step.isDrag,useRecordedMousedown:this.step.useRecordedMousedown,allEventsOnSameElement:this.step.allEventsOnSameElement,elementToFocusLocatedElement:y.elementToFocusLocatedElement,trackActiveElement:this.step.trackActiveElement,locatedElement:y.locatedElement,isRoot:y.isRoot},E=`
|
|
239
239
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
240
|
-
var dnd = ${
|
|
240
|
+
var dnd = ${vy.toString()};
|
|
241
241
|
var eventData = arguments[0];
|
|
242
242
|
var done = arguments[1];
|
|
243
243
|
return dnd.call(null, eventData, done);
|
|
244
|
-
`;return this.driver.executeCodeAsync(E,
|
|
244
|
+
`;return this.driver.executeCodeAsync(E,g,T)}let u=`
|
|
245
245
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
246
|
-
var dnd = ${
|
|
246
|
+
var dnd = ${Ty.toString()};
|
|
247
247
|
var eventData = arguments[0];
|
|
248
248
|
return dnd.call(null, eventData);
|
|
249
|
-
`,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?this.clickJs():this.step.button===2?this.driver.rightClick(r,i):this.driver.leftClick(r,i)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=o=>o.fireOnTarget||["drop","dragenter"].includes(o.event);return e.forEach(o=>Object.assign(o,{locatedElement:n(o)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var Hn,
|
|
249
|
+
`,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?this.clickJs():this.step.button===2?this.driver.rightClick(r,i):this.driver.leftClick(r,i)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=o=>o.fireOnTarget||["drop","dragenter"].includes(o.event);return e.forEach(o=>Object.assign(o,{locatedElement:n(o)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var Hn,Cy=w(()=>{"use strict";ue();Hn=class extends V{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:o}}=this,i=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(i),{evaluatedText:l}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(l,a)?{success:!0}:{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(l),actual:a}}}catch{return{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:l.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Py,KE,ra,ky=w(()=>{"use strict";Py=S(require("lodash"));ue();$();KE=C("evaluate-expression-step-action"),ra=class extends V{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{KE.info("runner running incoming params evaluation");let o=t.incomingParams||{};Py.isEmpty(o)&&(o=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let i=["context",...o.as.functionParameters],a=[t,...o.as.functionArguments],c=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,i.concat([c]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(o){let{stepResult:i}=this.sessionPlayerInit.commonConstants;throw{errorType:i.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:o.toString()},success:!1}}}}});var _y={};H(_y,{setText:()=>JE});var JE,Oy=w(()=>{"use strict";JE=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){tt()},window.addEventListener("unload",window.__unloadNavigator);let o=new Set(["keydown","keyup","keypress"]),i=15;function a(_){try{if(!t)return;let M=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return _.eventData&&(M.data=_.eventData.data),M}catch{}}function l(_){try{let M=document.createEvent("TextEvent");M.data=_.eventData.data;let j=1,z=_.eventData.locale||"en-US";return M.initTextEvent("textInput",!0,!0,window,_.eventData.data,j,z),M}catch{}}function c(_){return a(_)||l(_)}function d(_,M,j){try{return new KeyboardEvent(_,{bubbles:!0,cancelable:!0,location:M.location||0,key:M.key||"",ctrlKey:Boolean(j.ctrl),shiftKey:Boolean(j.shift),altKey:Boolean(j.alt),metaKey:Boolean(j.meta)})}catch{}}function m(_,M,j){try{let z=document.createEvent("KeyboardEvent");return z.initKeyEvent(_,!0,!0,null,Boolean(j.ctrl),Boolean(j.alt),Boolean(j.shift),Boolean(j.meta),M.key||"",0),z}catch{}}function u(_,M,j){try{let z=document.createEvent("Events");return z.initEvent(_,!0,!0),Object.assign(z,{altKey:Boolean(j.alt),ctrlKey:Boolean(j.ctrl),metaKey:Boolean(j.meta),shiftKey:Boolean(j.shift),keyCode:M.key||""}),z}catch{}}function f(_,M,j){return d(_,M,j)||m(_,M,j)||u(_,M,j)}function h(_){if(!o.has(_.event))return null;let M=_.eventData,j=M.modifiers||{},z=f(_.event,M,j);return Object.defineProperties(z,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(z,{_keyCode_:M.keyCode,_charCode_:M.charCode||0}),z}function g(_){return _.event==="textInput"?c(_):h(_)}function y(_,M){return(()=>{var z;return _.event==="textInput"&&!((z=M.quirks)!=null&&z.isAuth0Form)})()}function T(_,M){return _.event==="keyup"&&M.event==="keydown"?i:0}function E(_,M){let j=T(_,M);return Math.min(M.timeStamp-_.timeStamp,j)}function b(_){let M=Object.getOwnPropertyDescriptor(_,"value");if(!M)return;let j=_.value;_.value=`${j}#`,M.configurable&&delete _.value,_.value=j;let z=document.createEvent("HTMLEvents");z.initEvent("input",!0,!1),_.dispatchEvent(z),Object.defineProperty(_,"value",M)}function v(_){if(G(_.element))try{if(b(_.element),t)_.element.dispatchEvent(new Event("change"));else{let M=document.createEvent("HTMLEvents");M.initEvent("change",!1,!0),_.element.dispatchEvent(M)}}catch{}}function I(_,M,j){j?setTimeout(()=>{U(_)},E(M,j)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(_),tt())}function x(_,M){return(_==="change"||_==="blur")&&M.element.tagName==="OPTION"}function L(_,M,j){return x(_.type,M)?M.element.parentElement:j.locatedElement?getLocatedElement(j.locatedElement):M.element}function F(_,M){let j=_.firstChild,z;for(;j;){if(j.nodeType===3){if(M.offset--<=0)return j}else if(j.nodeType===1&&(z=F(j,M),z))return z;j=j.nextSibling}return null}function R(_,M){if(!(!_||!M)){if(!isNaN(M.start))Object.assign(_,{selectionStart:M.start,selectionEnd:M.end});else if(!isNaN(M.nodeOffset)){let j;if(_.firstChild?j=F(_,{offset:M.nodeOffset}):j=_,j){let z=window.getSelection(),pt=document.createRange();try{z.removeAllRanges(),pt.setStart(j,M.textOffset),pt.setEnd(j,M.textOffset),z.addRange(pt)}catch{}}}}}function A(_,M){return _==="submit"&&Boolean(M.action)}function k(_,M,j){if(M.isFocusable&&M.isSelectable(_)&&_.type!=="submit")try{R(M.element,j.eventData.selection)}catch{}let z=L(_,M,j);if(!z)throw new Error("could not find element");A(_.type,z)?z.submit():z.dispatchEvent(_)}function U(_){let M,j=_.events[_.eventIndex],z=_.events[++_.eventIndex];try{M=g(j)}catch(pt){return St(`exception in get event in text step:${pt.message}`)}if(y(j,_))return I(_,j,z);if(M)try{k(M,_,j)}catch(pt){return St(`exception in executeEvent in text step:${pt.message}`)}else if(_.noEventExecuter)_.noEventExecuter(_,j);else return St(`cannot execute event ${j.event}`);I(_,j,z)}function G(_){let M=_.tagName;return M==="INPUT"||M==="TEXTAREA"}function Y(_){return _.getAttribute?Boolean(_.getAttribute("contenteditable")==="true"):!1}function X(_,M){if(G(_.element)){_.element.value=M.eventData.text;let j=document.createEvent("Event");j.initEvent("input",!0,!1),_.element.dispatchEvent(j)}else _.isContentEditable&&(_.element.innerHTML=M.eventData.text)}function me(){var M;let _=document.activeElement;for(;(M=_.shadowRoot)!=null&&M.activeElement;)_=_.shadowRoot.activeElement;return _}function tt(_){let M={status:"done",result:_,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(M)}function St(_){_||="";let M={status:"failed",result:_,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(M)}try{let _=G(n.element);n.isContentEditable=Y(n.element),!_&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=_||n.isContentEditable,n.isSelectable=M=>M.type!=="keyup",n.noEventExecuter=X}catch(_){St(`exception in set text step:${_.message}`);return}let Nr=me();dispatchFocus(s.elementToFocusLocatedElement,Nr),U(n)}});var sa,Ly=w(()=>{"use strict";ue();B();sa=class extends V{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Le(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:o}=this,i=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:l}=o.codeSnippets;if(i.isDraftEditor&&l)return this.driver.executeJS(l(i.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let c={eventType:t,events:e,quirks:r,locatedElement:i.locatedElement,isRoot:i.isRoot,elementToFocusLocatedElement:i.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(Oy(),_y)),Promise.resolve().then(()=>(Dn(),Ln))]),u=`
|
|
250
250
|
var getLocatedElement = ${o.codeSnippets.getLocatedElementCode};
|
|
251
251
|
var dispatchFocus = ${m};
|
|
252
252
|
var setText = ${d.toString()};
|
|
253
253
|
var eventData = arguments[0];
|
|
254
254
|
var done = arguments[1];
|
|
255
255
|
return setText.call(null, eventData, done);
|
|
256
|
-
`,f=await this.driver.executeCodeAsync(u,a,c);return{success:Boolean((
|
|
256
|
+
`,f=await this.driver.executeCodeAsync(u,a,c);return{success:Boolean((h=f.value)==null?void 0:h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Le(t.seleniumElement),e[r]),r<e.length-1&&await ae(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(Le(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 Dy={};H(Dy,{runCode:()=>YE});var YE,My=w(()=>{"use strict";YE=function(s,e){var d;function t(m,u){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let T={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(T))}catch(y){let T=y.message.toLowerCase().includes("quota"),E=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||T||E){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let I={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(I)),T||E)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let o={},i={},a={},l=s.functionParams,c=s.transactionId;try{let m=r(s);m.push(o,i,a);let u=((d=s.function)==null?void 0:d.params)||l,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(c,{type:"promise"}),h.then(g=>{t(c,{status:"done",success:!0,result:{resultValue:g,exports:o,exportsTest:i,exportsGlobal:a}})},g=>{t(c,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:o,exportsTest:i,exportsGlobal:a}})})):t(c,{status:"done",success:!0,result:{resultValue:h,exports:o,exportsTest:i,exportsGlobal:a}})}catch(m){t(c,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:o,exportsTest:i,exportsGlobal:a}})}}});var na,vp,lr,oa=w(()=>{"use strict";na=S(require("lodash"));B();ue();$();le();vp=C("base-js-step-action"),lr=class extends V{isExceedingMaxResultSize(t,r){var n;try{let o=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,i=D.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>i;return o?a:(a&&vp.warn(`js result size exceeded ${i}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let n=`data-testim-${r}`;try{return window.sessionStorage.getItem(n)}catch(o){if(o.message.includes("sessionStorage")||o.message.includes("The operation is insecure")){let i=document.head.querySelector("#testim-storage-backup");return i?i.getAttribute(n):"{}"}throw o}},t)}constructJSFunParams(t){let r=t.incomingParams,n=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],o=[t.context,...r.as.functionArguments];return n.push(t.code),o.forEach(i=>{na.isObject(i)&&So(i,"seleniumElement",na.isEqual)}),{function:{params:n,args:o},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:n,step:{id:o=""}}=this,i=r.config.retryTimeout,a=r.data.timeToPlayStep-i,l=async()=>{let c;try{c=await this.executeGetStatus(t)}catch(u){vp.warn("failed to get js status",{err:u}),c={value:'{ "status": "exception" }'}}let d;try{d=JSON.parse((c==null?void 0:c.value)||"{}")}catch{vp.warn("non object value",{selRes:c}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===o);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-i<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=i,await ae(i),l()):{success:!0})};return l()}async executeInAut(t){let r=D.flags.experimentalPreCodeCompilation.isEnabled(),n=D.flags.experimentalAsyncCustomCode.isEnabled(),o=this.constructJSFunParams(t),i=o.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=o.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
|
|
257
257
|
${t.code}
|
|
258
258
|
};`:`function(${m.join(",")}) {
|
|
259
259
|
${t.code}
|
|
260
|
-
};`,o.function.params.pop()}let{codeSnippets:l}=this.sessionPlayerInit,{runCode:c}=await Promise.resolve().then(()=>(
|
|
260
|
+
};`,o.function.params.pop()}let{codeSnippets:l}=this.sessionPlayerInit,{runCode:c}=await Promise.resolve().then(()=>(My(),Dy)),d=`
|
|
261
261
|
${i?`var getLocatedElement = ${l.getLocatedElementCode};`:";"}
|
|
262
262
|
var runCode = ${c.toString()};
|
|
263
263
|
var eventData = arguments[0];
|
|
264
264
|
var funcToRun = ${a};
|
|
265
265
|
return runCode.call(null, eventData, funcToRun);
|
|
266
|
-
`;if(!r)return this.driver.executeJS(d,o);try{return await this.driver.executeJS(d,o)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:o={},tstConsoleLogs:i,nodeVersion:a,navigateToDifferentDomain:l}=t;o.exports&&(n.data.exports=o.exports);let c={nodeVersion:a,tstConsoleLogs:i,data:n.data};return this.isFailedResult(o.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:o,tstConsoleLogs:i},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:o.exportsTest,exportsGlobal:o.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:o={},tstConsoleLogs:i}=t;return{tstConsoleLogs:i,data:n.data,exportsGlobal:o.exportsGlobal,exportsTest:o.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:o.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),o={transactionId:`${r.testResultId}:${t.id}`,id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(o);let i=await this.checkStatus(o.transactionId);return this.checkCodeResponse(i)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var qt,
|
|
266
|
+
`;if(!r)return this.driver.executeJS(d,o);try{return await this.driver.executeJS(d,o)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:o={},tstConsoleLogs:i,nodeVersion:a,navigateToDifferentDomain:l}=t;o.exports&&(n.data.exports=o.exports);let c={nodeVersion:a,tstConsoleLogs:i,data:n.data};return this.isFailedResult(o.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:o,tstConsoleLogs:i},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:o.exportsTest,exportsGlobal:o.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:o={},tstConsoleLogs:i}=t;return{tstConsoleLogs:i,data:n.data,exportsGlobal:o.exportsGlobal,exportsTest:o.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:o.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),o={transactionId:`${r.testResultId}:${t.id}`,id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(o);let i=await this.checkStatus(o.transactionId);return this.checkCodeResponse(i)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var qt,Ny=w(()=>{"use strict";oa();qt=class extends lr{isFailedResult(e){return e===!1}}});var Ss,Uy=w(()=>{"use strict";oa();Ss=class extends lr{isFailedResult(e){return!e}}});var ia,Fy=w(()=>{"use strict";ue();B();Qi();ia=class extends V{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Le(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(Wn[t]),this.setWithValueApi(e)}}});var aa,By=w(()=>{"use strict";ue();Qi();aa=class extends V{async performAction(){var o,i;let e=this.context.config.os.startsWith("Mac");if(e&&!((o=this.step.keys)!=null&&o.mac)||!e&&!((i=this.step.keys)!=null&&i.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Wn[n])t.push(Wn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var jy={};H(jy,{selectOption:()=>XE});function XE(s,e){function t(r,n){let o=Element.prototype.matches,i=o&&isNativeFunction(o)?o:document.createElement(r.tagName).__proto__.matches;do{if(i.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(i=>{let a=document.createEvent("HTMLEvents");return a.initEvent(i,!0,!1),a}).forEach(i=>{if(e){n.dispatchEvent(i);return}r.dispatchEvent(i)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var $y=w(()=>{"use strict"});var ca,Wy=w(()=>{"use strict";ue();B();le();ca=class extends V{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,o=(await this.driver.getBrowserAndOS()).browserMajor,i=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!i||i&&o>=13&&!a)try{return await this.driver.elementIdClick(Le(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>($y(),jy)),c=D.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
|
|
267
267
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
268
268
|
const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
|
|
269
269
|
const selectOption = ${l.toString()};
|
|
270
270
|
return selectOption.apply(null, arguments);
|
|
271
|
-
`;return(f=(await this.driver.executeJS(d,r,c)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var la,
|
|
271
|
+
`;return(f=(await this.driver.executeJS(d,r,c)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var la,Vy=w(()=>{"use strict";ue();la=class extends V{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var QE,ua,Gy=w(()=>{"use strict";ue();QE=(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(){}}),ua=class extends V{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:n}=e,{width:o,height:i}=n,a=o/2,l=i/2,c=this.step.element.clickOffset;if(c&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:u}=c;this.sessionPlayerInit.utils.isWithinTargetRect(QE(i,o,0,0),m,u)&&(a=m,l=u)}let d={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(l)}};return await this.driver.hover(t,d),{success:!0}}}});var Hy={};H(Hy,{wheel:()=>ZE});var ZE,qy=w(()=>{"use strict";ZE=function(s,e){function r(a,l){function c(h,g,y){return y>h&&y<g}let d=a.pointerPosition||{},m=l.getBoundingClientRect(),u=d.originX&&c(m.left,m.left+m.width,d.originX)?d.originX:m.left+m.width/2,f=d.originY&&c(m.top,m.top+m.height,d.originY)?d.originY:m.top+m.height/2;return{x:u,y:f}}function n(a,l,c){let d=r(a,c),m=(l==null?void 0:l.modifiers)||{},u={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:d.x,clientY:d.y,bubbles:!0,cancelable:!0,ctrl:Boolean(m.ctrl),alt:Boolean(m.alt),shift:Boolean(m.shift),meta:Boolean(m.meta)};return new WheelEvent("wheel",u)}function o(a,l){if(a.length===0){e({state:"success"});return}if(!l)throw new Error("element not found");let c=a.shift(),d=n(c,s.eventData,l),m=a[0]?Math.min(a[0].timeStamp-c.timeStamp,200):200;l.dispatchEvent(d),setTimeout(()=>{o(a,l)},m)}let i=getLocatedElement(s.locatedElement);o(s.events,i)}});var pa,zy=w(()=>{"use strict";ue();pa=class extends V{async performAction(){var m;let{step:e,context:t}=this,{events:r,modifiers:n,button:o}=e;if(!(r!=null&&r.length))return;let i={events:r,eventData:{modifiers:n,button:o},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:l}=await Promise.resolve().then(()=>(qy(),Hy)),c=`
|
|
272
272
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
273
273
|
var wheel = ${l.toString()};
|
|
274
274
|
var eventData = arguments[0];
|
|
275
275
|
var done = arguments[1];
|
|
276
276
|
return wheel.call(null, eventData, done);
|
|
277
|
-
`;return{success:((m=(await this.driver.executeCodeAsync(c,a,i)).value)==null?void 0:m.state)==="success"}}}});var
|
|
277
|
+
`;return{success:((m=(await this.driver.executeCodeAsync(c,a,i)).value)==null?void 0:m.state)==="success"}}}});var Ky={};H(Ky,{downloadFileAndFireDropEvent:()=>eI});var eI,Jy=w(()=>{"use strict";eI=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let i=-1,a=0,l=[],c={endWithCallback:void 0,waitOn(){let d=++i;return function(m){d in l||(l[d]=m,a++,e.length===a&&c.endWithCallback(l))}},endWith(d){c.endWithCallback=d}};return c}function n(i,a,l){let c=new XMLHttpRequest;c.open("GET",i),c.responseType="blob",c.onload=function(){if(this.status>=200&&this.status<300)l({blob:c.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},c.onerror=function(){throw new Error("Failed to load blob")},c.send()}let o=r();e.forEach(i=>{n(i.url,i.name,o.waitOn())}),o.endWith(i=>{let a=createDropEvent(i);t.dispatchEvent(a)})}});var tI,da,Yy=w(()=>{"use strict";ue();$();le();tI=C("drop-file-step-action"),da=class extends V{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,o=this.getTarget(),i=D.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,i,tI),{downloadFileAndFireDropEvent:l}=await Promise.resolve().then(()=>(Jy(),Ky)),c=`
|
|
278
278
|
const getLocatedElement = ${e.getLocatedElementCode};
|
|
279
279
|
const createDropEvent = ${e.createDropEvent.toString()};
|
|
280
280
|
const downloadFileAndFireDropEvent = ${l.toString()};
|
|
281
281
|
return downloadFileAndFireDropEvent.apply(null, arguments)
|
|
282
|
-
`;return await this.driver.executeJS(c,o.locatedElement,a)}}});function
|
|
282
|
+
`;return await this.driver.executeJS(c,o.locatedElement,a)}}});function Zy(s={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
|
|
283
283
|
var input = getLocatedElement(locatedElement);
|
|
284
284
|
if(input) {
|
|
285
285
|
function parents(element, _elements) {
|
|
@@ -321,7 +321,7 @@ Please make sure the CLI has stable access to the internet. ${Ec()?"(Internal: n
|
|
|
321
321
|
input.removeAttribute("disabled");
|
|
322
322
|
input.focus();
|
|
323
323
|
}
|
|
324
|
-
}`}async function
|
|
324
|
+
}`}async function sI(s,e){let t=null;try{t=(await vc(s)).body}catch(n){if(rI.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let r=`${Xy.tmpdir()}/${e}`;return await Qy.promises.writeFile(r,t),r}function nI(s){return ie(s,e=>sI(e.url,e.name))}function oI(s,e){return e(s)}async function eb(s,e){let t=await nI(s),r=await ie(t,n=>oI(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var Xy,Qy,rI,tb=w(()=>{"use strict";Xy=S(require("os"));Ge();Qy=require("fs");B();$();rI=C("input-file-utils")});function aI(){return`async function downloadAndUpload(locatedElement, fileUrls) {
|
|
325
325
|
const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
|
|
326
326
|
const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
|
|
327
327
|
const attachTo = document.body || document.documentElement;
|
|
@@ -398,24 +398,24 @@ Please make sure the CLI has stable access to the internet. ${Ec()?"(Internal: n
|
|
|
398
398
|
element.dispatchEvent(new Event("change", { bubbles: true }));
|
|
399
399
|
}
|
|
400
400
|
element.removeEventListener("change", changeFiredHandler, true);
|
|
401
|
-
}`}var ma,fa,
|
|
401
|
+
}`}var ma,fa,rb=w(()=>{"use strict";tb();ue();$();B();le();ma=C("input-file-step-action"),fa=class extends V{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){ma.info("workaround - stepaction - move element to visible position");let n=`
|
|
402
402
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
403
|
-
var getVisibleElement = ${
|
|
403
|
+
var getVisibleElement = ${Zy(r)};
|
|
404
404
|
return getVisibleElement.apply(null, arguments);
|
|
405
|
-
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw ma.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(o)||f.startsWith(i)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ma.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Le(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=D.flags.overrideAzureStorageUrl.isEnabled(),n=D.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:o,context:i,step:a,stepActionUtils:l,driver:c}=this,d=await o.utils.addTokenToFileUrls(i.project.id,a.fileUrls,l.testimServicesApi,r,ma);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let
|
|
405
|
+
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw ma.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(o)||f.startsWith(i)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ma.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Le(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=D.flags.overrideAzureStorageUrl.isEnabled(),n=D.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:o,context:i,step:a,stepActionUtils:l,driver:c}=this,d=await o.utils.addTokenToFileUrls(i.project.id,a.fileUrls,l.testimServicesApi,r,ma);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await Nt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
|
|
406
406
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
407
|
-
const downloadAndUploadFile = ${
|
|
408
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await tb(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ga,ha,nb=w(()=>{"use strict";ga=require("url");ue();ha=class extends V{async updateBaseUrl(e){let t=new ga.URL(e),r=new ga.URL(this.context.recordedBaseUrl),n=new ga.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var ya,ob=w(()=>{"use strict";ue();B();ya=class extends V{async performAction(){await ae(this.step.durationMS||0)}}});var ba,ib=w(()=>{"use strict";ue();ba=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var qn,ab=w(()=>{"use strict";ue();qn=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.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.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ta,cb=w(()=>{"use strict";ue();Ta=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var lb,Sp,Ep,ub=w(()=>{"use strict";lb=S(require("@applitools/spec-driver-webdriverio"));io();Te();Sp=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=id["@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:lb.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=Z(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},Ep=new Sp});var db,pb,zn,mb=w(()=>{"use strict";db=S(require("lodash"));ue();$();ub();pb=C("pixel-validation-step-action"),zn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,l=await Ep.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),h={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};db.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),pb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:h}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){pb.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Ep.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Es,Ip=w(()=>{"use strict";hs();J();oa();Es=class extends lr{async executeCliCode(){var g,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(g=t.company)==null?void 0:g.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await gs(o,i,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ur,fb=w(()=>{"use strict";Ip();ur=class extends Es{isFailedResult(e){return e===!1}}});var wa,gb=w(()=>{"use strict";Ip();wa=class extends Es{isFailedResult(e){return!e}}});var va,hb=w(()=>{"use strict";hs();ue();J();va=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await fs(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof It?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Or,yb=w(()=>{"use strict";ue();Or=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,bb=w(()=>{"use strict";ue();ye=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Sa,Tb=w(()=>{"use strict";ue();Sa=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ea,wb=w(()=>{"use strict";ue();Ea=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function lI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Ia(s,e){lI(uI,e),e.registerLocateStepActionUtils(Vn.getUtils(s))}var uI,Rp=w(()=>{"use strict";hy();Ty();Cy();Py();_y();Dy();Uy();Fy();By();jy();Vy();Gy();Hy();Ky();Xy();sb();nb();ob();ib();ab();cb();mb();fb();gb();hb();yb();bb();Tb();wb();uI={locate:Vn,scroll:ea,mouse:ta,submit:la,text:sa,"special-key":ia,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":Ss,"skip-code-step":Ss,"element-code-step":Ss,"evaluate-expression":ra,"text-validation":Hn,"wait-for-text-validation":Hn,"select-option":ca,"drop-file":da,"input-file":fa,hover:ua,navigation:ha,wheel:pa,sleep:ya,refresh:ba,"keyboard-shortcut-step":aa,"api-validation":qn,"api-action":qn,"api-code-step":qt,"extract-text":Ta,"simple-ui-verification":zn,"wait-for-simple-ui-verification":zn,"cli-validation-download-file":Or,"cli-wait-for-download-file":Or,"network-validation-step":Or,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":wa,"node-package":va,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":Ea,"sfdc-recorded-step":Sa,"sfdc-step-login":ye,"sfdc-step-loginas":ye,"sfdc-step-logout":ye,"sfdc-step-sobjectcreate":ye,"sfdc-step-sobjectdelete":ye,"sfdc-step-findrecord":ye,"sfdc-step-quickaction":ye,"sfdc-step-sobjectedit":ye,"sfdc-step-sobjectvalidate":ye,"sfdc-step-launchapp":ye,"sfdc-step-wait-for-page-load":ye,"sfdc-step-closeconsoletabs":ye,"sfdc-step-relatedlistaction":ye,"sfdc-step-permission-validation":ye,"sfdc-step-convert-lead-to-opportunity":ye,"sfdc-step-quotelineeditor":ye,"sfdc-document-validation":Or,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var vb,pI,Is,Ap=w(()=>{"use strict";vb=["simple-ui-verification","wait-for-simple-ui-verification"],pI=[...vb,"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"],Is=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=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=pI.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return vb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var Eb={};G(Eb,{SeleniumTestPlayer:()=>Kn});var Sb,dI,Kn,xp=w(()=>{"use strict";B();Sb=require("@applitools/eyes-sdk-core");Mn();J();$();gp();py();Tp();Qi();fy();wp();Te();Rp();Ap();dI=C("SeleniumTestPlayer"),Kn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Is(Zi());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Z();this.driver=n??new Cr;let d=new Xi(this.driver);this.stepActionFactory=new c(d),Ia(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ji(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=my(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:Yi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Sb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){dI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Pp={};G(Pp,{WorkerSelenium:()=>Cp});function fI(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var Ra,mI,Cp,kp=w(()=>{"use strict";B();$e();$n();$();kt();ii();ne();mp();J();xp();Te();Qe();Ra=C("worker-selenium"),mI=1e9,Cp=class extends Ot{initPlayer(t){return new Kn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),ee.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new Ts(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),N("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,mI),await this.windowUtils.validatePageIsAvailable(),N("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof Et||d||m?new Et(`Page '${l}' is not available`):(Ra.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Wo(),initializedFromCache:Vo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=Z(),{driver:i,sessionPlayer:a}=r,l=n||"runner";ee.onWaitToTestComplete(this.id),fI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await Tn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof oe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(Ra.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(Ra.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let h={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),N("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),N("right after super.runTestOnce in workerSelenium");let u=await d();return N("right after runSeleniumTest"),u}catch(u){throw Ra.error("failed to run test once",{err:u}),u}}}});var Ib,Rb,He,gI,hI,_p,St,Aa=w(()=>{"use strict";Ib=S(require("ora")),Rb=S(require("jimp"));pe();Ge();he();$();ne();Te();le();He=C("mobile-grid-service"),gI="https://tdc.tricentis-cloud.com",hI="https://ui.headspin.io",_p=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===O.TESTIM_HEADSPIN?`${r||Za}/${tc}/devices`:t===O.TESTIM_TDC?`${r||ec}/${tc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:o})}catch(i){throw He.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let o=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw He.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t,r){let n=await $s(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,l,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let d=await Ll({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n){let{executionId:o,testId:i,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,f=t.capabilities,g=f.platformName,h;if(u===O.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=Z();h=T(t.capabilities)}else h=await this.getDeviceFromAppiumCapabilities(f,t,r,g,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,f);return await vr(l,o,i,a,"RUNNING",{device:h,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:a,executionId:o,testId:i,device:h,remoteResultLink:y,gridType:u}),h}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===O.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),i=Number(o[0]),a=Number(o[1]);return{scaleFactor:e.pixelRatio,width:i,height:a}}try{let{AppiumApi:o}=Z(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await Rb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,o,i,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:o,projectId:i,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,o);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ds}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?hI:gI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${Sd}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await vr(l,n,o,i,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,o=t.mobileApp,i=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:o,gridHost:e.host});return i?(D.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:i,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ml({gridAppId:i,gridId:e.gridId,projectId:r,gridType:n,appId:o.appId,gridHost:e.host})),i):t.getAppPathByGridType(n,e.gridId,o)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await pn({appId:e,projectId:t});return{appUrl:`${fe}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(vd*60))+1)*60*1e3,Math.max(wd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let a={[O.BROWSERSTACK]:{name:"Browserstack"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[O.P_CLOUDY]:{name:"pCloudy"}}[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Ib.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 Dl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),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:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,o=T.mobileApp,e.nativeApp=o}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let g=l||e.mobileApp.appId,h=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(h){let T=t.projectData.type,E=await this.verifyAppStillExistsOnGrid({gridAppId:h,gridData:m,projectType:T});E&&(He.info("app exists on grid, using gridAppId",{gridAppId:h,projectId:c,testResultId:a,executionId:i,mobileAppId:g}),n=h),!E&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:h,projectId:c,testResultId:a,executionId:i,mobileAppId:g}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:g})),!E&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!h&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:g})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:o,host:i,key:a,type:l,apiUrl:c}=t;if(l===O.BROWSERSTACK){let u=`${Ds}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a});return Array.isArray(f)?f.some(g=>g.app_url===e):!1}if(l===O.SAUCELABS){let f=`${i.includes("eu-central-1")?Rd:Id}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:f,user:o,key:a})).items.some(h=>h.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let u=`${c}/${rc}/apps`;return c||(u=`${l===O.TESTIM_HEADSPIN?Za:ec}/${rc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(g=>g.app_id===e)}if(l===O.TESTIM_TVC){let u=`${Ed}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token"}),!0}catch(g){return g.status!==404&&He.error("error while verifying app exists on TVC",{error:g}),!1}}if(l===O.P_CLOUDY){let u=await this.getPCloudyAuthToken(i,o,a),f=`https://${i}/api/drive`,g=await Tc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(g).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await be(e,void 0,n)}},St=new _p});function Ab({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!yI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function bI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function TI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function wI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&D.flags.enableBatchHeadSpin.isEnabled(),d=i&&(D.flags.enableBatchTDC.isEnabled()||D.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=D.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture`]:!0,...D.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:TI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:300}}}function xa(s){return"id"in s?s.id:s.packageName}function vI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function SI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=vI(n,t.gridData.type));let m=()=>i===void 0&&n?!0:typeof i=="string"?i!=="false":i;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":xa(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...o&&{"appium:appWaitActivity":`${o}, *`},...r&&{"appium:appPackage":xa(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Dr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:xa(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:xa(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function xb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=wI(i.type,o,n);return SI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Pa({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 ka({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?sc:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":sc:".*")}function EI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function II(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ca(s,Rs)}}function Cb(s,e,t){return s?Object.entries(s).reduce((r,[n,o])=>{if(e(n)){if(!t)return r[n]=o,r;let i=n.replace(t,"");r[i]=o}return r},{}):{}}function RI(s){return Cb(s,e=>e.startsWith("browserstack."),"browserstack.")}function AI(s){return Cb(s,e=>!e.startsWith("browserstack."))}function Pb(s){return!s||!kb(s)?"2.0.0":s}function kb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function _b({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,o=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,i=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&o.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&i.test(s),d=l||c;if(t){let m=kb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ca(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=EI(o,s),f=Pa({osVersion:l,mobileConfig:d}),g=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:g,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":h,"waldo:options":{token:u}};return Dr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=o,g=D.flags.enableAppium2pCloudy.isEnabled(),h=Pa({osVersion:l,mobileConfig:d}),y=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),E={...h!==".*"&&{pCloudy_DeviceVersion:h},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:i.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...E,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Ad),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return g&&(b=II(b)),t="",Dr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...g&&{appiumPrefix:Rs}})}function PI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Pa({osVersion:l,mobileConfig:d}),f=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),g=(0,Lr.omit)({...n.saucelabs},["automationName","platformName"]),h={...g["sauce:options"]};if(delete g["sauce:options"],_b({osVersion:g.platformVersion||u,projectType:s,appiumVersion:h.appiumVersion})){let T={debug:!0,networkLogs:!0},E={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:Pb(h.appiumVersion),deviceName:f,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ca(g,Rs),"sauce:options":{...T,...E,...(0,Lr.omit)(h,"appiumVersion")}};return Dr({projectType:s,sessionCaps:b,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":o.user,"saucelabs.key":o.key,platformVersion:u,deviceName:f,tags:Object.values(i),name:i.testResultId,build:i.executionId,...g,...h};return Dr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function kI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Pa({osVersion:l,mobileConfig:d}),f=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),g=RI(n.browserstack),h=(0,Lr.omit)(AI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:E}=n.browserstack||{},b=D.flags.enableAppium2BrowserStack.isEnabled();if(b||_b({osVersion:h.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:g.appiumVersion})){let R={userName:o.user,accessKey:o.key,appiumVersion:b?"2.0.1":Pb(g.appiumVersion),projectName:y||i.project,buildName:T||i.executionId,debug:!0,networkLogs:!0},I={"appium:platformVersion":u,"appium:deviceName":f,...Ca(h,Rs),"bstack:options":{...R,...(0,Lr.omit)(g,"appiumVersion")}};return Dr({projectType:s,sessionCaps:I,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:h.platformVersion||u,device:h.deviceName||f,realDevice:!0,name:E||i.testResultId,project:y||i.project,build:T||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...h,...Ca(g,"browserstack.")};return Dr({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function _I(s){if(O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type)return xb(s);if(O.TESTIM_TVC===s.gridInfo.type)return xI(s);if(O.P_CLOUDY===s.gridInfo.type)return CI(s);if(O.SAUCELABS===s.gridInfo.type)return PI(s);if(O.BROWSERSTACK===s.gridInfo.type)return kI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function OI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,l={};return n==="dynamic"&&(!o&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!i&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),o&&(l.manufacturer=o),i&&(l.os_version=i),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Ob(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);Ab({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=St.getGridConnection(e),l=_I(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let m=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",u=OI(r,o==null?void 0:o.mobile);if(!(0,Lr.isEmpty)(u)){let f=Object.entries(u).map(([g,h])=>h.split(",").map(y=>y===".*"||y==="="?"":`${g}:${y}`).join(",")).join(" ").trim();l[`${m}:selector`]=f}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l,d=D.flags.increaseTDCRequestTimeout.isEnabled();return{...a,desiredCapabilities:l,...d&&{connectionRetryTimeout:48e4},capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function Lb(s){var g,h;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Ab({nativeAppMetadata:r,appPath:o,gridInfo:t}),bI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((h=(g=l.mobile)==null?void 0:g.staticAllocation)==null?void 0:h.deviceUdid),m=await St.getGridDirectConnection(t,d),f=xb({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Db(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,i=Dr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete i.app,i}function Mb(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 Lr,Rs,yI,Op=w(()=>{"use strict";le();ne();Aa();Lr=require("lodash");B();pe();Rs="appium:",yI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var _a,Ub=w(()=>{"use strict";_a=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Oa,Fb=w(()=>{"use strict";B();Oa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Js;this.getLinksFromUnescapeHTML=Ys}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Lp,La,Bb=w(()=>{"use strict";$();Lp=C("mobile-frame-locator-mock"),La=class{foundFrameCallback(){return Lp.info("foundFrameCallback-mock invoked"),{}}locate(){return Lp.info("locate-mock invoked"),{}}async findFrame(){return Lp.info("findFrame-mock invoked"),{}}}});var LI,$b,jb,As,Dp=w(()=>{"use strict";LI=S(require("webdriverio")),$b=require("@applitools/eyes-sdk-core");Ub();Tp();$();Fb();wp();Te();Rp();Bb();Ap();jb=C("appium-test-player"),As=class{constructor(e,t,r,n=LI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Z(),m=new Oa(this.driver);this.stepActionFactory=new c(m),Ia(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Is(Zi()),this.sessionPlayer=new a(e,{tabService:new _a,cookieUtils:void 0,FrameLocator:La,portSelector:Yi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:$b.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),jb.info("appium session deleted",{...o}))}catch(i){jb.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=Z();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function DI(s){return await be(`${s}/api/status`)}async function Wb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function Vb(s){if((await DI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Gb=w(()=>{"use strict";Ge()});var Hb={};G(Hb,{WorkerLocalTma:()=>Fp});var Mr,Mp,Np,Up,Fp,qb=w(()=>{"use strict";Ge();Op();$n();B();$();kt();Dp();Te();Gb();Aa();Mr=C("worker-appium"),Mp=class extends Error{},Np=class extends Error{},Up=class extends Error{},Fp=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new As(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Z(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}async getBrowserOnce(t,r,n,o){var R;if(ee.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:l}=this.options;await Vb(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:I}=await St.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=I}let g=u==="android"?t.androidActivityWait:null,h=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!h)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:E,version:b},v]=await Promise.all([this.getAppStateFromDevice(i,a,T),Wb(i,a)]).catch(I=>{throw this.handleDeviceNotFoundError(I),I});if(Mr.info("device status and app state",{deviceStatus:v,appInstalled:E,version:b,executionId:this.executionId,testResultId:this.testResultId}),!E&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!E&&y&&(await this.installApp(i,a,y),Mr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let I={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(R=this.options.projectData)==null?void 0:R.name}-${this.options.project}`},L=Db({projectType:u,nativeAppMetadata:h,appPath:y,androidActivityWait:g,sessionTags:I,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),U={capabilities:{udid:a,...L}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:U,executionId:this.executionId,testResultId:this.testResultId});let A=await this.requestNewAppiumSessionFromTma(i,U,h);this.sessionData=A;let x=await m.attach({sessionId:A.sessionId,capabilities:L});this.device=await St.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:x.sessionId,testResultId:this.testResultId,nativeAppMetadata:h,sessionCaps:x.capabilities})}catch(I){throw Mr.error("failed to start application",{err:I}),I}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Up(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await be(i)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Nt(n);await js(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Np(c,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Mp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=Z(),{sessionPlayer:i}=r,a=n||"runner";ee.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var Kb={};G(Kb,{WorkerAppium:()=>Bp});var zb,Nr,Bp,Jb=w(()=>{"use strict";Op();zb=require("linkedom");$n();$();kt();Dp();Te();Aa();ne();cs();Nr=C("worker-appium"),Bp=class extends Ot{initPlayer(t){return new As(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){ee.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await St.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.id}`},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await St.lockDevice(o,this.options.deviceUdid),f=await Lb(u)):f=Ob(u),Nr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Mb(f)});let g=this.getServerAddressFromGrid();this.activeSession=await i.remote(f),this.device=await St.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options);let h=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(h),Nr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Nr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await(t==null?void 0:t.getOrientation())}catch(o){Nr.error("failed to keep appium session alive",{err:o}),r!=null&&r.AppiumSessionTerminatedError&&o instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&Tg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Nr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=Z(),{sessionPlayer:a}=r,l=n||"runner";ee.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let g=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:T,path:E}=await St.getHeadSpinDeviceConnection(this.options.gridData,g);c=`${h}://${y}:${T}${E}`}else c=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(f=this.options.company)==null?void 0:f.companyId,device:this.device},a.playbackManager.appiumApi=new o(c,this.activeSession.sessionId,zb.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let g=await new Promise((y,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await i.drain(),g.stepsResults=null,g.resultId=this.testResultId,{...g,...t.seleniumPerfStats.getStats()}}catch(g){throw Nr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:g}),this.stopKeepAlive(),g}};try{return await super.runTestOnce(t,r),await m()}catch(g){throw Nr.error("failed to run test once",{err:g}),g}}}});var Da,Yb=w(()=>{"use strict";B();Mn();J();Da=class{constructor(e){this.id=e;this.driver=new Cr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Xb,Ma,Qb=w(()=>{"use strict";Xb=S(require("ws"));B();Ma=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new Xb.default(this._cdpUrl,{timeout:e}),r=Xt(o=>{t.once("open",o)}),n=Xt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((l,c)=>{this._cdpCallbacks.set(o,{resolve:l,reject:c})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var Ua,jp,Na,Zb=w(()=>{"use strict";B();Ua=S(require("chrome-launcher"));Hu();Qb();fn();jp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ma}async init(e){var g,h,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Mi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((g=m.desiredCapabilities)==null?void 0:g.chromeOptions.args)??[],...((T=(y=(h=m.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...Ua.Launcher.defaultFlags().filter(E=>E!=="--disable-extensions")];this.chrome=await Ua.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await yr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),rs(()=>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}},Na=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new jp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var $p={};G($p,{WorkerExtension:()=>Jn});function MI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function eT(s){return MI(s)?s:new Error(s)}var ut,Jn,Fa=w(()=>{"use strict";$e();J();$n();B();$();kt();ne();Yb();Zb();Qe();ut=C("worker-ext"),Jn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Na(this.id):new Da(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Wo(),initializedFromCache:Vo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return ee.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;N("WorkerExtension runTestOnce");let i=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,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))throw u;return ut.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw ut.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(N("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){ee.onWaitToTestStart(this.id),ee.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(g){throw ut.warn("failed to run test via CDP",{err:g}),g}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let g=await e.getRunTestUrl();ee.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,g,u),l(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}ee.onWaitToTestComplete(this.id);let h=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),T.type=Vs.BROWSER_CLOSED,h.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),E=await fc(T,h.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(E.success),E.reason)}catch(R){ut.error("Could not update the grid about the test status",{err:R})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),E.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ut.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),E.keepAliveIssue=b),{...E,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:o}),eT(T)}finally{m.unregisterToClosedBrowser(y)}}catch(g){throw ut.warn("failed to start url",{err:g}),eT(g)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Vp={};G(Vp,{WorkerExtensionSingleBrowser:()=>Wp});var NI,UI,Wp,Gp=w(()=>{"use strict";$e();B();$();ap();kt();Fa();NI=C("base-worker"),UI=500,Wp=class extends Jn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Bn(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return ee.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(NI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;N("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ae(UI)}}});var Hp,qp,Ba,tT=w(()=>{"use strict";Mn();pe();$e();Nu();Qe();Yu();J();$();ne();Xh();ei();Hp=C("worker-manager"),qp=0,Ba=class{constructor(e){this.customExtensionLocalLocation=e;this.parallelCount=0;this.workersCount=new Map;this.combinedTestResults={};this.onWorkerFinished=e=>{this.workersCount.delete(e)};this.runWorkersIfNeeded=async(...e)=>{for(;this.workersCount.size<this.parallelCount&&this.executionQueue.hasMoreTests();)await this.runWorker(...e)};this.runWorker=async(...e)=>{let t=this.executionQueue.getNext();if(!t)return;let r=await this.createWorker(t.runConfig.browserValue,...e);this.workersCount.set(qp,r),r.id=qp,qp++,r.run(t,this.onWorkerFinished,this.runWorkersIfNeeded,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(qb(),Hb))).WorkerLocalTma:(await Promise.resolve().then(()=>(Jb(),Kb))).WorkerAppium;default:return Nn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Gp(),Vp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Fa(),$p))).WorkerExtension}else switch(r){case(Er.find(n=>n===r)&&Nn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Gp(),Vp))).WorkerExtensionSingleBrowser;case Er.find(n=>n===r):return(await Promise.resolve().then(()=>(Fa(),$p))).WorkerExtension;case yn.find(n=>n===r):return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;default:throw new P(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return N("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{N("after new Worker",r.mode)}}async runTests(e,t,r,n,o,i,a,l,c){if(e&&e.length===0)return;let d=!1,m=0,u=(f,g)=>new Promise(h=>{var tt,pt,dr,_,M,j,K,dt;let y=o.project,T=e.length;this.parallelCount=l,this.executionQueue=new Vi(r,n,e,o,i,t),this.combinedTestResults={};let E=((tt=o.company)==null?void 0:tt.ucid)||"",b=(pt=o.company)==null?void 0:pt.companyId,v=(dr=o.company)==null?void 0:dr.name,R=o.source||"cli",I=o.user,L=(_=o.company)==null?void 0:_.planType,U=(M=o.company)==null?void 0:M.isStartUp,A=(j=o.projectData)==null?void 0:j.name,x=(K=o.projectData)==null?void 0:K.type,k=o.lightweightMode,F=(dt=o.gridData)==null?void 0:dt.type,H=(zt,Lt,we,Ha,Xn,qa)=>(m++,Lg({executionId:r,projectId:y,testId:Lt,resultId:we,ucid:E,companyId:b,companyName:v,projectName:A,companyPlan:L,source:R,user:I,lightweightMode:k,isStartUp:U,projectType:x,appSource:qa,gridType:F}),t.testStartAndReport(zt,r,we,Ha,Xn)),z=async(zt,Lt,we,Ha,Xn,qa)=>{var ed,td,rd;m--;let rt={...(k==null?void 0:k.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...o.host&&{gridHost:o.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),o.grid||o.gridId?(rt.gridName=o.grid||((ed=o.gridData)==null?void 0:ed.name),rt.gridType=(td=o.gridData)==null?void 0:td.type,rt.gridProvider=(rd=o.gridData)==null?void 0:rd.provider):o.localTmaUrl?(rt.gridName="local-tma-from-options",rt.gridType="local-tma"):o.useLocalChromeDriver?(rt.gridName="local-chrome-driver-from-options",rt.gridType="local-chrome"):o.useChromeLauncher?(rt.gridName="chrome-launcher-from-options",rt.gridType="local-chrome"):o.browserstack?rt.gridName="browserstack-from-options":o.saucelabs&&(rt.gridName="saucelabs-from-options"),await t.testEndAndReport(zt,we,r,Ha,Xn,rt).catch(kT=>Hp.error("testEndAndReport threw an error",{err:kT})),Xn)return;this.combinedTestResults[we.resultId]=we,Dg({executionId:r,projectId:y,testId:Lt,resultId:we.resultId,result:we,ucid:E,companyId:b,companyName:v,projectName:A,companyPlan:L,source:R,user:I,lightweightMode:k,logger:Hp,isStartUp:U,projectType:x,appSource:qa}),c&&!we.success&&(this.executionQueue.stop(),d=!0),(Object.keys(this.combinedTestResults).length===T||d&&m===0)&&h(this.combinedTestResults)},X=(zt,Lt)=>{this.combinedTestResults[Lt.resultId]=Lt,t.onTestIgnored(zt,Lt.resultId),m--,(Object.keys(this.combinedTestResults).length===T||d&&m===0)&&h(this.combinedTestResults)},me=(zt,Lt)=>t.onGridSlot(zt,Lt);o.userData={loginData:{...jt(),refreshToken:jo(),authData:jt(),token:f,userAccessKey:g},projectId:o.project,company:o.company,servicesUrl:fe},N("in localStrategy before createWorker"),this.runWorkersIfNeeded(o,this.customExtensionLocalLocation,r,H,z,me,X)});try{let f=await xt(),g=await $o(),h=await u(f,g);if(d)throw new Jt;return h}catch(f){throw Hp.error("failed running parallel workers",{executionId:r,err:f}),f}}}});var Yn,ja,zp,$a,rT=w(()=>{"use strict";Yn=S(require("lodash"));B();$();pe();ne();$e();is();Tu();Nu();he();Qe();kt();th();J();tT();ei();({CLI_MODE:ja}=Ut),zp=C("test-plan-runner"),$a=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=jt(),m=new Ba(this.customExtensionLocalLocation),u=async()=>{let y=o.beforeParallel||1,T=!0,E=await m.runTests(e,l,i,a,o,n,d,y,T);Object.assign(c,E)},f=async()=>{let y=lo||o.parallel,T=!1;N("right before this.workerManager.runTests");let E=await m.runTests(t,l,i,a,o,n,d,y,T);N("right after this.workerManager.runTests"),Object.assign(c,E)},g=async()=>{let y=o.afterParallel||1,T=!1,E=await m.runTests(r,l,i,a,o,n,d,y,T);Object.assign(c,E)};Mg({executionId:i,projectId:o.project}),N("right before runBeforeTests");try{return await u(),N("right before runTestPlanTests"),await f(),N("right after runTestPlanTests"),await g(),c}catch(y){if(zp.error("error running test plan",{err:y}),y instanceof Jt)return l.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw y}finally{await h()}async function h(){var T,E,b,v;if((T=o.lightweightMode)!=null&&T.disablePixelValidation)return;if(o.mode===ja.SELENIUM){let[{getSessionPlayer:R},{makeSDK:I}]=await Promise.all([Promise.resolve().then(()=>(Te(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:L}=R();await L.closeBatch(i,I);return}let y;try{if(!((v=(b=(E=o.company)==null?void 0:E.activePlan)==null?void 0:b.premiumFeatures)!=null&&v.applitools)||(y=await Cl(o.project),Yn.default.isEmpty(y)||!i))return;let{runKey:R,url:I}=y;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:I,apiKey:R}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,v,R;let c=se(),d=n.project;lc(c),e.forEach(I=>Object.assign(I,{isBeforeTestPlan:!0})),r.forEach(I=>Object.assign(I,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Li(m,n,i,a),f=Yn.default.chain(m).map(I=>{var L;return((L=I.overrideTestConfig)==null?void 0:L.name)||""}).uniq().compact().value(),g=(f==null?void 0:f.length)===1?f[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(I=>I.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,h);N("before testListInfoPromise");let T=await y;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||ee.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,c,l,g),N("before runTestAllPhases");let E=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,o||"All Tests",u);return N("before executionEnd"),await u.executionEnd(c),N("after executionEnd"),{results:E,executionId:c,testPlanName:o,configName:g}}async runTestPlans(e,t){zp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Yn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await pl(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==ja.APPIUM&&await Yl(e,r(c)),await ie(l,async d=>{var g;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((g=d.mobileApp)==null?void 0:g.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await dg(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,u,f,m,t);ee.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(R=>({executionId:R,status:Jl(n[m][R])})),E=Object.keys(n[m]).map(R=>n[m][R]).reduce((R,I)=>Object.assign(R,I),{}),b=Jl(E);Object.assign(o,E);let v=b?T[0].executionId:T.find(R=>!R.status).executionId;return await cl(i,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;zp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),N("before getSuite");let r=await vf(e,t);if(N("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;N("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===ja.APPIUM&&(a=await pn({appId:e.appId,projectId:e.project})),await ie(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==ja.APPIUM&&await Yl(e,c),N("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,o,null,t,i);return N("right after runTestPlan"),await ee.onTestPlanFinished(d.results,o,this.startTime,d.executionId,i),d})}async run(e){let t=xn(),r=[];Hs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Yn.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await ee.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var iT={};G(iT,{init:()=>iR,run:()=>tR});async function FI(s){let e=s.project,t=await ml(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),gn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ms}function BI(s,e){var i,a,l,c,d,m,u,f;let t=Eo(e.activePlan),r=s.parallel;if(t==="free"&&r>nT)throw new P(`The free plan allows only ${nT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let g=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!g)throw new P("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 h=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!h&&(console.warn(`
|
|
409
|
-
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&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let
|
|
407
|
+
const downloadAndUploadFile = ${aI()};
|
|
408
|
+
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await eb(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ga,ha,sb=w(()=>{"use strict";ga=require("url");ue();ha=class extends V{async updateBaseUrl(e){let t=new ga.URL(e),r=new ga.URL(this.context.recordedBaseUrl),n=new ga.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var ya,nb=w(()=>{"use strict";ue();B();ya=class extends V{async performAction(){await ae(this.step.durationMS||0)}}});var ba,ob=w(()=>{"use strict";ue();ba=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var qn,ib=w(()=>{"use strict";ue();qn=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.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.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ta,ab=w(()=>{"use strict";ue();Ta=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var cb,Sp,Ep,lb=w(()=>{"use strict";cb=S(require("@applitools/spec-driver-webdriverio"));io();Te();Sp=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=od["@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:cb.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=Z(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},Ep=new Sp});var pb,ub,zn,db=w(()=>{"use strict";pb=S(require("lodash"));ue();$();lb();ub=C("pixel-validation-step-action"),zn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,l=await Ep.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};pb.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(g,i.applitoolsStepSettings),ub.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){ub.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Ep.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Es,Ip=w(()=>{"use strict";hs();K();oa();Es=class extends lr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await gs(o,i,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ur,mb=w(()=>{"use strict";Ip();ur=class extends Es{isFailedResult(e){return e===!1}}});var wa,fb=w(()=>{"use strict";Ip();wa=class extends Es{isFailedResult(e){return!e}}});var va,gb=w(()=>{"use strict";hs();ue();K();va=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await fs(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof It?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var _r,hb=w(()=>{"use strict";ue();_r=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,yb=w(()=>{"use strict";ue();ye=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Sa,bb=w(()=>{"use strict";ue();Sa=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ea,Tb=w(()=>{"use strict";ue();Ea=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function cI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Ia(s,e){cI(lI,e),e.registerLocateStepActionUtils(Vn.getUtils(s))}var lI,Rp=w(()=>{"use strict";gy();by();xy();Cy();ky();Ly();Ny();Uy();Fy();By();Wy();Vy();Gy();zy();Yy();rb();sb();nb();ob();ib();ab();db();mb();fb();gb();hb();yb();bb();Tb();lI={locate:Vn,scroll:ea,mouse:ta,submit:la,text:sa,"special-key":ia,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":Ss,"skip-code-step":Ss,"element-code-step":Ss,"evaluate-expression":ra,"text-validation":Hn,"wait-for-text-validation":Hn,"select-option":ca,"drop-file":da,"input-file":fa,hover:ua,navigation:ha,wheel:pa,sleep:ya,refresh:ba,"keyboard-shortcut-step":aa,"api-validation":qn,"api-action":qn,"api-code-step":qt,"extract-text":Ta,"simple-ui-verification":zn,"wait-for-simple-ui-verification":zn,"cli-validation-download-file":_r,"cli-wait-for-download-file":_r,"network-validation-step":_r,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":wa,"node-package":va,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":Ea,"sfdc-recorded-step":Sa,"sfdc-step-login":ye,"sfdc-step-loginas":ye,"sfdc-step-logout":ye,"sfdc-step-sobjectcreate":ye,"sfdc-step-sobjectdelete":ye,"sfdc-step-findrecord":ye,"sfdc-step-quickaction":ye,"sfdc-step-sobjectedit":ye,"sfdc-step-sobjectvalidate":ye,"sfdc-step-launchapp":ye,"sfdc-step-wait-for-page-load":ye,"sfdc-step-closeconsoletabs":ye,"sfdc-step-relatedlistaction":ye,"sfdc-step-permission-validation":ye,"sfdc-step-convert-lead-to-opportunity":ye,"sfdc-step-quotelineeditor":ye,"sfdc-document-validation":_r,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var wb,uI,Is,Ap=w(()=>{"use strict";wb=["simple-ui-verification","wait-for-simple-ui-verification"],uI=[...wb,"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"],Is=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=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=uI.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return wb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var Sb={};H(Sb,{SeleniumTestPlayer:()=>Kn});var vb,pI,Kn,xp=w(()=>{"use strict";B();vb=require("@applitools/eyes-sdk-core");Mn();K();$();gp();uy();Tp();Qi();my();wp();Te();Rp();Ap();pI=C("SeleniumTestPlayer"),Kn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Is(Zi());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Z();this.driver=n??new xr;let d=new Xi(this.driver);this.stepActionFactory=new c(d),Ia(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ji(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=dy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:Yi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:vb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){pI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Pp={};H(Pp,{WorkerSelenium:()=>Cp});function mI(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var Ra,dI,Cp,kp=w(()=>{"use strict";B();$e();$n();$();kt();ii();ne();mp();K();xp();Te();Qe();Ra=C("worker-selenium"),dI=1e9,Cp=class extends Ot{initPlayer(t){return new Kn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),ee.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new Ts(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),N("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,dI),await this.windowUtils.validatePageIsAvailable(),N("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof Et||d||m?new Et(`Page '${l}' is not available`):(Ra.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Wo(),initializedFromCache:Vo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=Z(),{driver:i,sessionPlayer:a}=r,l=n||"runner";ee.onWaitToTestComplete(this.id),mI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await Tn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof oe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(Ra.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(Ra.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});i.start(),N("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),N("right after super.runTestOnce in workerSelenium");let u=await d();return N("right after runSeleniumTest"),u}catch(u){throw Ra.error("failed to run test once",{err:u}),u}}}});var Eb,Ib,He,fI,gI,_p,vt,Aa=w(()=>{"use strict";Eb=S(require("ora")),Ib=S(require("jimp"));pe();Ge();he();$();ne();Te();le();He=C("mobile-grid-service"),fI="https://tdc.tricentis-cloud.com",gI="https://ui.headspin.io",_p=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===O.TESTIM_HEADSPIN?`${r||Za}/${tc}/devices`:t===O.TESTIM_TDC?`${r||ec}/${tc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:o})}catch(i){throw He.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let o=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw He.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t,r){let n=await $s(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,l,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let d=await Ll({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n){let{executionId:o,testId:i,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,f=t.capabilities,h=f.platformName,g;if(u===O.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=Z();g=T(t.capabilities)}else g=await this.getDeviceFromAppiumCapabilities(f,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,f);return await wr(l,o,i,a,"RUNNING",{device:g,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:a,executionId:o,testId:i,device:g,remoteResultLink:y,gridType:u}),g}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===O.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),i=Number(o[0]),a=Number(o[1]);return{scaleFactor:e.pixelRatio,width:i,height:a}}try{let{AppiumApi:o}=Z(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await Ib.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,o,i,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:o,projectId:i,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,o);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ds}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?gI:fI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${vd}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await wr(l,n,o,i,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,o=t.mobileApp,i=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:o,gridHost:e.host});return i?(D.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:i,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ml({gridAppId:i,gridId:e.gridId,projectId:r,gridType:n,appId:o.appId,gridHost:e.host})),i):t.getAppPathByGridType(n,e.gridId,o)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await pn({appId:e,projectId:t});return{appUrl:`${fe}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(wd*60))+1)*60*1e3,Math.max(Td,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let a={[O.BROWSERSTACK]:{name:"Browserstack"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[O.P_CLOUDY]:{name:"pCloudy"}}[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Eb.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 Dl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),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:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,o=T.mobileApp,e.nativeApp=o}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(g){let T=t.projectData.type,E=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});E&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=g),!E&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!E&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:o,host:i,key:a,type:l,apiUrl:c}=t;if(l===O.BROWSERSTACK){let u=`${Ds}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===O.SAUCELABS){let f=`${i.includes("eu-central-1")?Id:Ed}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:f,user:o,key:a})).items.some(g=>g.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let u=`${c}/${rc}/apps`;return c||(u=`${l===O.TESTIM_HEADSPIN?Za:ec}/${rc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===O.TESTIM_TVC){let u=`${Sd}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token"}),!0}catch(h){return h.status!==404&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===O.P_CLOUDY){let u=await this.getPCloudyAuthToken(i,o,a),f=`https://${i}/api/drive`,h=await Tc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await be(e,void 0,n)}},vt=new _p});function Rb({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"&&!hI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function yI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function bI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function TI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&D.flags.enableBatchHeadSpin.isEnabled(),d=i&&(D.flags.enableBatchTDC.isEnabled()||D.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=D.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture`]:!0,...D.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:bI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:300}}}function xa(s){return"id"in s?s.id:s.packageName}function wI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function vI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=wI(n,t.gridData.type));let m=()=>i===void 0&&n?!0:typeof i=="string"?i!=="false":i;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":xa(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...o&&{"appium:appWaitActivity":`${o}, *`},...r&&{"appium:appPackage":xa(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Lr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:xa(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:xa(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Ab({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=TI(i.type,o,n);return vI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Pa({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 ka({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?sc:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":sc:".*")}function SI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function EI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ca(s,Rs)}}function xb(s,e,t){return s?Object.entries(s).reduce((r,[n,o])=>{if(e(n)){if(!t)return r[n]=o,r;let i=n.replace(t,"");r[i]=o}return r},{}):{}}function II(s){return xb(s,e=>e.startsWith("browserstack."),"browserstack.")}function RI(s){return xb(s,e=>!e.startsWith("browserstack."))}function Cb(s){return!s||!Pb(s)?"2.0.0":s}function Pb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function kb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,o=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,i=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&o.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&i.test(s),d=l||c;if(t){let m=Pb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ca(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function AI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=SI(o,s),f=Pa({osVersion:l,mobileConfig:d}),h=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),g=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:h,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":g,"waldo:options":{token:u}};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=o,h=D.flags.enableAppium2pCloudy.isEnabled(),g=Pa({osVersion:l,mobileConfig:d}),y=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),E={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:i.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...E,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Rd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=EI(b)),t="",Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Rs}})}function CI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Pa({osVersion:l,mobileConfig:d}),f=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Or.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],kb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},E={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:Cb(g.appiumVersion),deviceName:f,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ca(h,Rs),"sauce:options":{...T,...E,...(0,Or.omit)(g,"appiumVersion")}};return Lr({projectType:s,sessionCaps:b,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":o.user,"saucelabs.key":o.key,platformVersion:u,deviceName:f,tags:Object.values(i),name:i.testResultId,build:i.executionId,...h,...g};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function PI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Pa({osVersion:l,mobileConfig:d}),f=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=II(n.browserstack),g=(0,Or.omit)(RI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:E}=n.browserstack||{},b=D.flags.enableAppium2BrowserStack.isEnabled();if(b||kb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let I={userName:o.user,accessKey:o.key,appiumVersion:b?"2.0.1":Cb(h.appiumVersion),projectName:y||i.project,buildName:T||i.executionId,debug:!0,networkLogs:!0},x={"appium:platformVersion":u,"appium:deviceName":f,...Ca(g,Rs),"bstack:options":{...I,...(0,Or.omit)(h,"appiumVersion")}};return Lr({projectType:s,sessionCaps:x,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:E||i.testResultId,project:y||i.project,build:T||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ca(h,"browserstack.")};return Lr({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function kI(s){if(O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type)return Ab(s);if(O.TESTIM_TVC===s.gridInfo.type)return AI(s);if(O.P_CLOUDY===s.gridInfo.type)return xI(s);if(O.SAUCELABS===s.gridInfo.type)return CI(s);if(O.BROWSERSTACK===s.gridInfo.type)return PI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function _I(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,l={};return n==="dynamic"&&(!o&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!i&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),o&&(l.manufacturer=o),i&&(l.os_version=i),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function _b(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);Rb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=kI(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let m=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",u=_I(r,o==null?void 0:o.mobile);if(!(0,Or.isEmpty)(u)){let f=Object.entries(u).map(([h,g])=>g.split(",").map(y=>y===".*"||y==="="?"":`${h}:${y}`).join(",")).join(" ").trim();l[`${m}:selector`]=f}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l,d=D.flags.increaseTDCRequestTimeout.isEnabled();return{...a,desiredCapabilities:l,...d&&{connectionRetryTimeout:48e4},capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function Ob(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Rb({nativeAppMetadata:r,appPath:o,gridInfo:t}),yI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=Ab({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Lb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,i=Lr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete i.app,i}function Db(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 Or,Rs,hI,Op=w(()=>{"use strict";le();ne();Aa();Or=require("lodash");B();pe();Rs="appium:",hI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var _a,Nb=w(()=>{"use strict";_a=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Oa,Ub=w(()=>{"use strict";B();Oa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Js;this.getLinksFromUnescapeHTML=Ys}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Lp,La,Fb=w(()=>{"use strict";$();Lp=C("mobile-frame-locator-mock"),La=class{foundFrameCallback(){return Lp.info("foundFrameCallback-mock invoked"),{}}locate(){return Lp.info("locate-mock invoked"),{}}async findFrame(){return Lp.info("findFrame-mock invoked"),{}}}});var OI,jb,Bb,As,Dp=w(()=>{"use strict";OI=S(require("webdriverio")),jb=require("@applitools/eyes-sdk-core");Nb();Tp();$();Ub();wp();Te();Rp();Fb();Ap();Bb=C("appium-test-player"),As=class{constructor(e,t,r,n=OI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Z(),m=new Oa(this.driver);this.stepActionFactory=new c(m),Ia(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Is(Zi()),this.sessionPlayer=new a(e,{tabService:new _a,cookieUtils:void 0,FrameLocator:La,portSelector:Yi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:jb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Bb.info("appium session deleted",{...o}))}catch(i){Bb.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=Z();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function LI(s){return await be(`${s}/api/status`)}async function $b(s,e){return await be(`${s}/api/devices/${e}/status`)}async function Wb(s){if((await LI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Vb=w(()=>{"use strict";Ge()});var Gb={};H(Gb,{WorkerLocalTma:()=>Fp});var Dr,Mp,Np,Up,Fp,Hb=w(()=>{"use strict";Ge();Op();$n();B();$();kt();Dp();Te();Vb();Aa();Dr=C("worker-appium"),Mp=class extends Error{},Np=class extends Error{},Up=class extends Error{},Fp=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new As(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Z(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}async getBrowserOnce(t,r,n,o){var I;if(ee.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:l}=this.options;await Wb(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:x}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=x}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:E,version:b},v]=await Promise.all([this.getAppStateFromDevice(i,a,T),$b(i,a)]).catch(x=>{throw this.handleDeviceNotFoundError(x),x});if(Dr.info("device status and app state",{deviceStatus:v,appInstalled:E,version:b,executionId:this.executionId,testResultId:this.testResultId}),!E&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!E&&y&&(await this.installApp(i,a,y),Dr.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:`${(I=this.options.projectData)==null?void 0:I.name}-${this.options.project}`},L=Lb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:x,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),F={capabilities:{udid:a,...L}};Dr.info("requesting new appium session from TMA",{tmaSessionSettings:F,executionId:this.executionId,testResultId:this.testResultId});let R=await this.requestNewAppiumSessionFromTma(i,F,g);this.sessionData=R;let A=await m.attach({sessionId:R.sessionId,capabilities:L});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Dr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:A.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:A.capabilities})}catch(x){throw Dr.error("failed to start application",{err:x}),x}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Up(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await be(i)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Nt(n);await js(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Np(c,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Mp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=Z(),{sessionPlayer:i}=r,a=n||"runner";ee.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Dr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Dr.error("failed to run test once",{err:c}),c}}}});var zb={};H(zb,{WorkerAppium:()=>Bp});var qb,Mr,Bp,Kb=w(()=>{"use strict";Op();qb=require("linkedom");$n();$();kt();Dp();Te();Aa();ne();cs();Mr=C("worker-appium"),Bp=class extends Ot{initPlayer(t){return new As(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){ee.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.id}`},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(o,this.options.deviceUdid),f=await Ob(u)):f=_b(u),Mr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Db(f)});let h=this.getServerAddressFromGrid();this.activeSession=await i.remote(f),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let g=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),Mr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Mr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await(t==null?void 0:t.getOrientation())}catch(o){Mr.error("failed to keep appium session alive",{err:o}),r!=null&&r.AppiumSessionTerminatedError&&o instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&bg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Mr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=Z(),{sessionPlayer:a}=r,l=n||"runner";ee.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let h=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:g,hostname:y,port:T,path:E}=await vt.getHeadSpinDeviceConnection(this.options.gridData,h);c=`${g}://${y}:${T}${E}`}else c=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(f=this.options.company)==null?void 0:f.companyId,device:this.device},a.playbackManager.appiumApi=new o(c,this.activeSession.sessionId,qb.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let h=await new Promise((y,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await i.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...t.seleniumPerfStats.getStats()}}catch(h){throw Mr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:h}),this.stopKeepAlive(),h}};try{return await super.runTestOnce(t,r),await m()}catch(h){throw Mr.error("failed to run test once",{err:h}),h}}}});var Da,Jb=w(()=>{"use strict";B();Mn();K();Da=class{constructor(e){this.id=e;this.driver=new xr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Yb,Ma,Xb=w(()=>{"use strict";Yb=S(require("ws"));B();Ma=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new Yb.default(this._cdpUrl,{timeout:e}),r=Xt(o=>{t.once("open",o)}),n=Xt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((l,c)=>{this._cdpCallbacks.set(o,{resolve:l,reject:c})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var Ua,jp,Na,Qb=w(()=>{"use strict";B();Ua=S(require("chrome-launcher"));Hu();Xb();fn();jp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ma}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Mi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...Ua.Launcher.defaultFlags().filter(E=>E!=="--disable-extensions")];this.chrome=await Ua.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await hr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),rs(()=>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}},Na=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new jp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var $p={};H($p,{WorkerExtension:()=>Jn});function DI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Zb(s){return DI(s)?s:new Error(s)}var ut,Jn,Fa=w(()=>{"use strict";$e();K();$n();B();$();kt();ne();Jb();Qb();Qe();ut=C("worker-ext"),Jn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Na(this.id):new Da(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Wo(),initializedFromCache:Vo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return ee.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;N("WorkerExtension runTestOnce");let i=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,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))throw u;return ut.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw ut.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(N("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){ee.onWaitToTestStart(this.id),ee.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw ut.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();ee.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}ee.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),T.type=Vs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),E=await fc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(E.success),E.reason)}catch(I){ut.error("Could not update the grid about the test status",{err:I})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),E.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ut.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),E.keepAliveIssue=b),{...E,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:o}),Zb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),Zb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Vp={};H(Vp,{WorkerExtensionSingleBrowser:()=>Wp});var MI,NI,Wp,Gp=w(()=>{"use strict";$e();B();$();ap();kt();Fa();MI=C("base-worker"),NI=500,Wp=class extends Jn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Bn(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return ee.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(MI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;N("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ae(NI)}}});var Hp,Ba,eT=w(()=>{"use strict";Mn();pe();$e();Nu();Qe();Yu();K();$();ne();Yh();ei();Hp=C("worker-manager"),Ba=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,n),n.id=t,n.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(Hb(),Gb))).WorkerLocalTma:(await Promise.resolve().then(()=>(Kb(),zb))).WorkerAppium;default:return Nn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Gp(),Vp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Fa(),$p))).WorkerExtension}else switch(r){case(Sr.find(n=>n===r)&&Nn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Gp(),Vp))).WorkerExtensionSingleBrowser;case Sr.find(n=>n===r):return(await Promise.resolve().then(()=>(Fa(),$p))).WorkerExtension;case yn.find(n=>n===r):return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;default:throw new P(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return N("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{N("after new Worker",r.mode)}}async runTests(e,t,r,n,o,i,a,l,c){if(e&&e.length===0)return;let d=!1,m=0,u=(f,h)=>new Promise(g=>{var tt,St,Nr,_,M,j,z,pt;let y=o.project,T=e.length;this.parallelCount=l,this.executionQueue=new Vi(r,n,e,o,i,t),this.combinedTestResults={};let E=((tt=o.company)==null?void 0:tt.ucid)||"",b=(St=o.company)==null?void 0:St.companyId,v=(Nr=o.company)==null?void 0:Nr.name,I=o.source||"cli",x=o.user,L=(_=o.company)==null?void 0:_.planType,F=(M=o.company)==null?void 0:M.isStartUp,R=(j=o.projectData)==null?void 0:j.name,A=(z=o.projectData)==null?void 0:z.type,k=o.lightweightMode,U=(pt=o.gridData)==null?void 0:pt.type,G=(zt,Lt,we,Ha,Xn,qa)=>(m++,Og({executionId:r,projectId:y,testId:Lt,resultId:we,ucid:E,companyId:b,companyName:v,projectName:R,companyPlan:L,source:I,user:x,lightweightMode:k,isStartUp:F,projectType:A,appSource:qa,gridType:U}),t.testStartAndReport(zt,r,we,Ha,Xn)),Y=async(zt,Lt,we,Ha,Xn,qa)=>{var Zp,ed,td;m--;let rt={...(k==null?void 0:k.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...o.host&&{gridHost:o.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),o.grid||o.gridId?(rt.gridName=o.grid||((Zp=o.gridData)==null?void 0:Zp.name),rt.gridType=(ed=o.gridData)==null?void 0:ed.type,rt.gridProvider=(td=o.gridData)==null?void 0:td.provider):o.localTmaUrl?(rt.gridName="local-tma-from-options",rt.gridType="local-tma"):o.useLocalChromeDriver?(rt.gridName="local-chrome-driver-from-options",rt.gridType="local-chrome"):o.useChromeLauncher?(rt.gridName="chrome-launcher-from-options",rt.gridType="local-chrome"):o.browserstack?rt.gridName="browserstack-from-options":o.saucelabs&&(rt.gridName="saucelabs-from-options"),await t.testEndAndReport(zt,we,r,Ha,Xn,rt).catch(PT=>Hp.error("testEndAndReport threw an error",{err:PT})),Xn)return;this.combinedTestResults[we.resultId]=we,Lg({executionId:r,projectId:y,testId:Lt,resultId:we.resultId,result:we,ucid:E,companyId:b,companyName:v,projectName:R,companyPlan:L,source:I,user:x,lightweightMode:k,logger:Hp,isStartUp:F,projectType:A,appSource:qa}),c&&!we.success&&(this.executionQueue.stop(),d=!0),(Object.keys(this.combinedTestResults).length===T||d&&m===0)&&g(this.combinedTestResults)},X=(zt,Lt)=>{this.combinedTestResults[Lt.resultId]=Lt,t.onTestIgnored(zt,Lt.resultId),m--,(Object.keys(this.combinedTestResults).length===T||d&&m===0)&&g(this.combinedTestResults)},me=(zt,Lt)=>t.onGridSlot(zt,Lt);for(o.userData={loginData:{...jt(),refreshToken:jo(),authData:jt(),token:f,userAccessKey:h},projectId:o.project,company:o.company,servicesUrl:fe},N("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(o,this.customExtensionLocalLocation,r,G,Y,me,X)});try{let f=await xt(),h=await $o(),g=await u(f,h);if(this.workers.size>0&&this.workers.clear(),d)throw new Jt;return g}catch(f){throw Hp.error("failed running parallel workers",{executionId:r,err:f}),f}}}});var Yn,ja,qp,$a,tT=w(()=>{"use strict";Yn=S(require("lodash"));B();$();pe();ne();$e();is();Tu();Nu();he();Qe();kt();eh();K();eT();ei();({CLI_MODE:ja}=Ut),qp=C("test-plan-runner"),$a=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=jt(),m=new Ba(this.customExtensionLocalLocation),u=async()=>{let y=o.beforeParallel||1,T=!0,E=await m.runTests(e,l,i,a,o,n,d,y,T);Object.assign(c,E)},f=async()=>{let y=lo||o.parallel,T=!1;N("right before this.workerManager.runTests");let E=await m.runTests(t,l,i,a,o,n,d,y,T);N("right after this.workerManager.runTests"),Object.assign(c,E)},h=async()=>{let y=o.afterParallel||1,T=!1,E=await m.runTests(r,l,i,a,o,n,d,y,T);Object.assign(c,E)};Dg({executionId:i,projectId:o.project}),N("right before runBeforeTests");try{return await u(),N("right before runTestPlanTests"),await f(),N("right after runTestPlanTests"),await h(),c}catch(y){if(qp.error("error running test plan",{err:y}),y instanceof Jt)return l.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw y}finally{await g()}async function g(){var T,E,b,v;if((T=o.lightweightMode)!=null&&T.disablePixelValidation)return;if(o.mode===ja.SELENIUM){let[{getSessionPlayer:I},{makeSDK:x}]=await Promise.all([Promise.resolve().then(()=>(Te(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:L}=I();await L.closeBatch(i,x);return}let y;try{if(!((v=(b=(E=o.company)==null?void 0:E.activePlan)==null?void 0:b.premiumFeatures)!=null&&v.applitools)||(y=await Cl(o.project),Yn.default.isEmpty(y)||!i))return;let{runKey:I,url:x}=y;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:x,apiKey:I}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,v,I;let c=se(),d=n.project;lc(c),e.forEach(x=>Object.assign(x,{isBeforeTestPlan:!0})),r.forEach(x=>Object.assign(x,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Li(m,n,i,a),f=Yn.default.chain(m).map(x=>{var L;return((L=x.overrideTestConfig)==null?void 0:L.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(x=>x.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,g);N("before testListInfoPromise");let T=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||ee.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,c,l,h),N("before runTestAllPhases");let E=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,o||"All Tests",u);return N("before executionEnd"),await u.executionEnd(c),N("after executionEnd"),{results:E,executionId:c,testPlanName:o,configName:h}}async runTestPlans(e,t){qp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Yn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await pl(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==ja.APPIUM&&await Yl(e,r(c)),await ie(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await pg(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);ee.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(I=>({executionId:I,status:Jl(n[m][I])})),E=Object.keys(n[m]).map(I=>n[m][I]).reduce((I,x)=>Object.assign(I,x),{}),b=Jl(E);Object.assign(o,E);let v=b?T[0].executionId:T.find(I=>!I.status).executionId;return await cl(i,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;qp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),N("before getSuite");let r=await wf(e,t);if(N("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;N("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===ja.APPIUM&&(a=await pn({appId:e.appId,projectId:e.project})),await ie(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==ja.APPIUM&&await Yl(e,c),N("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,o,null,t,i);return N("right after runTestPlan"),await ee.onTestPlanFinished(d.results,o,this.startTime,d.executionId,i),d})}async run(e){let t=xn(),r=[];Hs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Yn.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await ee.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var oT={};H(oT,{init:()=>oR,run:()=>eR});async function UI(s){let e=s.project,t=await ml(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),gn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ms}function FI(s,e){var i,a,l,c,d,m,u,f;let t=Eo(e.activePlan),r=s.parallel;if(t==="free"&&r>sT)throw new P(`The free plan allows only ${sT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let h=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!h)throw new P("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 g=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
409
|
+
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&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let h=e.tvcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new P(`Your license allows only ${g} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((m=s.gridData)==null?void 0:m.type)===O.TESTIM_TDC){let h=e.tdcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(!n)return;let o=(f=(u=e.activePlan)==null?void 0:u.premiumFeatures)==null?void 0:f.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function BI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await UI(s)}catch(t){if([P,Ms].some(r=>t instanceof r))throw t;zp.error("could not validate cli account",{err:t})}}function jI(s){let e=jt();return mf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function $I(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(D.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Tt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(ji(),jh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>($i(),Vh));r.init(s)}}function WI(s,e){let{branch:t,autoDetect:r}=s;if(Tg(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function VI(s,e){let{id:t,type:r}=e,o=nT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&D.flags.sfdcHybridCompany.isEnabled(),i=xn();o&&(s.sfdcCredential=await il({projectId:t,branch:i}))}function GI(s,e){let{id:t,storageBaseUrl:r,storageType:n,name:o,activePlan:i={}}=e,a=Boolean(i.isPoc),l=Boolean(i.isStartUp),c=Eo(i);c==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<rT?rT:s.newBrowserWaitTimeout),D.setCompanyId(t),D.setIsPOC(a),D.setIsStartUp(l),D.setPlanType(c),Pt.setPlanType(c),s.company={ucid:"",companyId:t,storageBaseUrl:r,storageType:n,name:o,planType:c,isPOC:a,isStartUp:l,activePlan:i}}function HI(s,e){s.editorUrl=Ls||e.editorUrl}function qI(s,e){s.allGrids=e}function zI(s,e){s.authData=e}function KI(s,e){let{id:t,name:r,type:n,defaults:o}=e;D.setProjectId(t),D.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function JI(s){var e;s.gridData=await dg(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function YI(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}function XI(s,e){s.getBrowserRetries=["android","ios"].includes(e.type||"")?1:s.getBrowserRetries}async function QI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(yt("user-override-file",t),s.mockNetworkRules=await ef(s.overrideMappingFile))}async function ZI(s,e){N("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await $f(),N("in runner.js after checkNpmVersion"),await BI(s),N("in runRunner before tunnel.connect"),await mi(s),N("in runRunner after tunnel.connect");let a=await new $a(e).run(s);return N("before tunnel.disconnect"),await fi(s),await sR(s.slotService,t,s.company.companyId),N("after tunnel.disconnect and gridService.keepAlive.end"),a}function tR(s){var e;Pt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
|
|
410
410
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
411
411
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
412
|
-
`)}function
|
|
413
|
-
Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),
|
|
412
|
+
`)}function rR(s,e,t){s==="redis"&&Rn.start(t,e),s==="mongo"&&En.start(e)}async function sR(s,e,t){s==="redis"&&await Rn.end(t,e),s==="mongo"&&await En.end(e)}function nR(s,e){var o,i,a,l,c,d;let t=D.flags.redisSlotManager.isEnabled(),r=((o=s.projectData)==null?void 0:o.type)==="ios"||((i=s.projectData)==null?void 0:i.type)==="android",n=t&&r;if(e.followL2CPlan){let m=(l=(a=e.l2cLicense)==null?void 0:a.shadowCatalogId)==null?void 0:l.includes("testim_mobile"),u=!!((c=e.tvcLicense)!=null&&c.maxParallel);n&&u&&m&&(s.slotService="redis")}!e.followL2CPlan&&n&&((d=e.mobile)!=null&&d.maxParallel)&&(s.slotService="redis")}async function oR(s){var h,g,y;N("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o}=s,i=$I(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n===q.SELENIUM)),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{});let{authData:a,editorConfig:l,companyByProjectId:c,projectById:d,branchName:m,allGrids:u}=await dn(s);if(s.printGrids){let T=u.sort((E,b)=>E.type.localeCompare(b.type));console.table(T.reduce((E,b)=>{class v{constructor(L,F){this.Type=L,this.Browsers=F}}let I=Object.entries(b.browsers||{"N/A":""}).map(x=>x.join(":")).join(", ");return E[b.name]=new v(b.type,I),E},{})),process.exit(0)}if(await i,N("after featureFlagsReady and socketConnected"),HI(s,l),GI(s,c),KI(s,d),YI(s,d),XI(s,d),WI(s,m),qI(s,u),zI(s,a),await VI(s,d),await JI(s),FI(s,c),nR(s,c),D.flags.clearRunnerFileCache.isEnabled())try{await Yr(),zp.info("runner file cache cleared")}catch(T){zp.error("failed to clear runner file cache",{err:T})}(h=s.lightweightMode)!=null&&h.disableLabs||await Nn.loadLabFeatures(d.id,c.activePlan),((g=s.lightweightMode)==null?void 0:g.type)==="turboMode"&&(D.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&console.log(`
|
|
413
|
+
Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),rR(s.slotService,e,c.id),jI(e),await QI(s),tR(s);let f=xn();await ee.setOptions(s,f)}var nT,rT,sT,zp,eR,iT=w(()=>{"use strict";nT=S(require("lodash"));B();uu();hu();$e();is();cs();ss();Tu();he();Qe();Bt();$();kt();pe();ne();K();tT();Fi();Yu();le();Pn();Vl();rT=30*60*1e3,sT=1,zp=C("runner");eR=ZI});function aT(s){s.get("/",(e,t)=>{let r=Kp();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:lu()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());tu({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var cT=w(()=>{"use strict";ni();Jp();uu()});var Yp,lT,xs,Wa,uT=w(()=>{"use strict";Yp=S(require("chalk"));hs();lT=require("express");$();K();xs=C("cli-router"),Wa=(0,lT.Router)();Wa.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:o,testResultId:i,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!o||!i||typeof a!="number"||!l||typeof c!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:i,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d,nodePackageParams:n.nodePackageParams};try{let u=await gs(t,r,n,o,i,a,l,c,d);u.success||(console.log(Yp.default.red(u.result.resultValue)),xs.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){xs.error("failed to run cli code",{err:u,...m}),console.log(Yp.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});Wa.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:o,stepResultId:i,timeout:a}=s.body;if(!t||typeof o!="object"||!r||typeof n!="number"||!i||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let l={stepId:t,testResultId:r,retryIndex:n,stepResultId:i,timeout:a,packageData:o};try{let c=await fs(t,r,n,o,i,a);xs.info("installed packages successfully",l),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof It){xs.error("failed to install node packages",{err:c,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof oe){xs.error("timeout installing node package",{err:c,...l}),e.status(200).json({success:!1,code:"timeout"});return}xs.error("failed to install node packages",{err:c,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var pT=w(()=>{"use strict";uT()});var gT={};H(gT,{orchestrateRoutes:()=>iR});function iR(s){let e=(0,mT.default)();s(e),e.use(Xp.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,fT.default)()),e.use(Xp.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:_e||cd?"*":["http://localhost:3000","https://app.testim.io","https://staging.testim.io","https://playground.testim.io","https://app.staging.testim.cc","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","chrome-extension://cnhebigpldnbbmpagckbodchceefampm","https://tta-crm.tricentis.com"]};return e.use("*",(0,dT.default)(r)),aT(e),e.use("/cliJs",Wa),e.use((n,o)=>{o.status(404).send("Endpoint Not Found")}),e}var dT,mT,Xp,fT,hT=w(()=>{"use strict";dT=S(require("cors")),mT=S(require("express")),Xp=S(require("body-parser")),fT=S(require("compression"));cT();pT();pe()});var bT={};H(bT,{init:()=>aR});async function aR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(hT(),gT));return new Promise((o,i)=>{let a=()=>{};t&&(Wm(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let l=n(a),c=yT.createServer(l);c.listen(s,e),c.on("error",d),c.on("listening",m);function d(u){if(u.syscall!=="listen")return i(u);switch(u.code){case"EACCES":case"EPERM":return i(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return i(new P(`Port ${s} is already in use, is another Testim instance running?`));default:return i(u)}}function m(){let{port:u}=c.address();console.log(`Running on port: ${u}`),cR()}})}async function cR(){await require("prompts")({name:"",type:"text",message:'Type the word "stop" or Press Ctrl + C.',validate:t=>t.toUpperCase().trim()==="STOP"}),console.log("Exiting Testim CLI"),process.exit(0)}var yT,TT=w(()=>{"use strict";yT=S(require("http"));Qe();K()});var AT={};H(AT,{getStartedWithStart:()=>Kp,runAgentMode:()=>dR});async function dR(s){var r;let e;if(await br(s.playerLocation,s.canary),s.startTestimBrowser){await gR();try{e=await fR(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new P('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(TT(),bT));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(xp(),Ne(Sb)))},6e3),t.init(s)}function Kp(){return IT}function wT(s){try{return process.kill(s,0)}catch{return!1}}async function mR(s,e,t){let r=pr.join(Ft,`chrome-${sn}-process`),n=3e3,o=()=>{Ce.rmSync(r,{recursive:!0}),console.log(`
|
|
414
414
|
|
|
415
|
-
Browser session ended`),process.exit(0)};if(await ge(r)){let f=JSON.parse(Ce.readFileSync(r));if(
|
|
416
|
-
`).map(o=>o.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await
|
|
417
|
-
`):""}overrideMimeType(t){if([Ee.LOADING,Ee.DONE].includes(this.readyState))throw new
|
|
415
|
+
Browser session ended`),process.exit(0)};if(await ge(r)){let f=JSON.parse(Ce.readFileSync(r));if(wT(f.pid)){let h=()=>wT(f.pid)?setTimeout(h,n):o();return h(),{webdriverApi:f}}}let i=await Bo();await ge(Cs)||await Ce.promises.mkdir(Cs,{recursive:!0});let l=[...RT(Cs,e,t,i).desiredCapabilities.chromeOptions.args,...Ga.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],c={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await Ga.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Cs,chromePath:i,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await hr(`localhost:${m.port}`)};return Ce.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",o),m.process.once("close",o),{webdriverApi:u}}async function fR(s){let e=`${yd}/extension/testim-full-master.zip`,t=pr.basename(e),r=pr.join(Ft,t),n=pr.join(Ft,`${t}__unzipped__`),o=!(s.ext||s.extensionPath);if(o&&await ge(r)){let f=await Ce.promises.stat(r);o=Date.now()-uR>f.mtimeMs}if(await Ce.promises.mkdir(Ft,{recursive:!0}),o){let f=(0,ST.default)("Downloading Testim Editor").start();await Je(e,r);try{await nt(r,n)}catch{await Ce.promises.rm(r,{recursive:!0,force:!0}),await Je(e,r);try{await nt(r,n)}catch{throw await Ce.promises.rm(r,{recursive:!0,force:!0}),f.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await Ce.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let i=s.extensionPath?null:(await Ce.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await mR(s,i,n);await Zs({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=RT(Cs,i,s.extensionPath,s.chromeBinaryLocations),{WebDriver:l}=(Mn(),Ne(Sh)),{SeleniumPerfStats:c}=(us(),Ne(Kg)),d=new l;d.seleniumPerfStats=new c;let m=await d.initClient(a);IT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await hr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function RT(s,e,t,r){let n=e?[e]:[],o=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&o.push(`--load-extension=${t}`),{logLevel:lR,desiredCapabilities:{chromeOptions:{args:o,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function gR(){if(await ge(Va))try{let{webSocketDebuggerUrl:s}=await hR();await yR(s),await Ce.promises.unlink(Va)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Ce.promises.unlink(Va)}}async function hR(){let s=await Ce.promises.readFile(Va,{encoding:"utf8"}),[e,t]=s.split(`
|
|
416
|
+
`).map(o=>o.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await hr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function yR(s,e=100){let t=await bR(s,e);return Xt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function bR(s,e=100){let t=new ET.default(s,{timeout:e}),r=Xt(o=>{t.once("open",o)}).then(()=>{t.removeAllListeners()}),n=Xt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}var vT,ST,ET,Ce,pr,Ga,lR,uR,Cs,pR,Va,IT,Jp=w(()=>{"use strict";vT=S(require("ms")),ST=S(require("ora")),ET=S(require("ws")),Ce=S(require("fs")),pr=S(require("path")),Ga=S(require("chrome-launcher"));pe();tn();K();Xc();B();lR=co?"verbose":"silent",uR=(0,vT.default)("1h"),Cs=pr.join(Ft,"profile"),pR="DevToolsActivePort",Va=pr.join(Cs,pR);IT=!1});var JD=require("source-map-support/register");var oo=S(require("os")),ks=S(require("url")),_s=S(require("http")),za=S(require("https")),Zn=S(require("form-data")),eo=class{constructor(){this.onloadstart=null;this.onprogress=null;this.onabort=null;this.onerror=null;this.onload=null;this.ontimeout=null;this.onloadend=null;this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]||=[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let o of r)o==null||o.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},to=class extends eo{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(t!=null)if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let o=0;o<t.byteLength;o++)r[o]=n[o];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=t.byteOffset,o=new Uint8Array(t.buffer);for(let i=0;i<t.byteLength;i++)r[i]=o[i+n];this._body=r}else if(typeof t=="object"&&t instanceof Zn.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()}},Ps=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}},ro=class extends Error{},so=class extends Error{},no=class extends Error{},dr=class extends Error{},Ee=class extends eo{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=_s.globalAgent;this.nodejsHttpsAgent=za.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 (${oo.type()} ${oo.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Ee.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new to(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){Ee.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&&!ks.parse(r,!1,!0).protocol)throw new ro("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new no(`HTTP method ${t} is not allowed in XHR`);let o=this._parseUrl(r);n===void 0&&(n=!0),this._method=t,this._url=o,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(Ee.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!==Ee.OPENED)throw new dr("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||n.startsWith("sec-")||n.startsWith("proxy-")||(r=r.toString(),n in this._loweredHeaders?(t=this._loweredHeaders[n],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[n]=t,this._headers[t]=r))}send(t){if(this.readyState!==Ee.OPENED)throw new dr("XHR readyState must be OPENED");if(this._request)throw new dr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new so(`Unsupported protocol ${this._url.protocol}`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let r=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
|
|
417
|
+
`):""}overrideMimeType(t){if([Ee.LOADING,Ee.DONE].includes(this.readyState))throw new dr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new Ps("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new so("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,o=(this._url.protocol==="http:"?_s:za).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 Zn.default&&t.pipe(o),this._request=o,this.timeout&&o.setTimeout(this.timeout,()=>this._onHttpTimeout(o)),o.on("response",i=>this._onHttpResponse(o,i)),o.on("error",()=>this._onHttpRequestError(o)),this.upload._startUpload(o),this._request===o&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof Zn.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",o=>this._onHttpResponseData(r,o)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=_s.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Ee.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ee.LOADING&&this._setReadyState(Ee.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ee.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(Ee.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ee.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ee.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new Ps(t);r.lengthComputable=this._lengthComputable,r.loaded=this._loadedBytes,r.total=this._totalBytes,this.dispatchEvent(r)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let r,n,o,i=this.nodejsBaseUrl===null?t:ks.resolve(this.nodejsBaseUrl,t),a=ks.parse(i,!1,!0);return a.hash=null,a.auth&&(o!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?o||(o=a.auth):(o||(o=a.substring(0,r)),n||(n=a.substring(r+1)))),(o||n)&&(a.auth=`${o}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let o=r.toLowerCase();this._privateHeaders[o]||(this._mimeOverride!==null&&o==="content-type"&&(n=this._mimeOverride),this._responseHeaders[o]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let o=0;o<t.length;o++)n[o]=t[o];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"}},Pe=Ee;Pe.SyntaxError=ro,Pe.ProgressEvent=Ps,Pe.SecurityError=no,Pe.XMLHttpRequest=Ee,Pe.InvalidStateError=dr,Pe.XMLHttpRequestUpload=to,Pe.UNSENT=0,Pe.OPENED=1,Pe.HEADERS_RECEIVED=2,Pe.LOADING=3,Pe.DONE=4;Object.assign(global,{xhr2:Pe,XMLHttpRequest:Pe});var xT=S(require("semver"));$e();Vl();Bt();tn();var Qp=S(require("chalk")),CT=require("events");ne();fn();K();ne();Go();$();var sf=S(require("os")),Gl=S(require("path")),Hl=S(require("chalk")),Xo=require("fs");pe();function nf(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=sf.homedir();(0,Xo.mkdirSync)(Gl.resolve(n,".testim_logs"),{recursive:!0});let o=Gl.resolve(n,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${o}`),md&&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(i=>i.includes("player-require-path"))&&(console.log(Hl.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(Hl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Xo.writeFileSync)(o,`${s}
|
|
418
418
|
${s==null?void 0:s.stack}
|
|
419
419
|
|
|
420
|
-
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Qs();var
|
|
420
|
+
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Qs();var uv=C("process-handler"),of=!1;function pv(s){return s instanceof Error?1:of?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:o})=>[t,o].includes(de.SKIPPED)||[t,o].includes(de.FAILED)&&n===Ye.EVALUATING?!1:r!==!0)?1:0)}function dv(){try{Zt("chromedriver").stop()}catch{}}function af(){of=!0}async function ql(s){s!=null&&s.stack&&(es?console.error(s,s.stack):nf(s)),dv(),await uv.waitForFlush(),process.exit(pv(s))}he();$();le();var TR=C("cli-entry");function wR(s){if(!xT.satisfies(process.version,s))throw new P(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=18,t=20,r=Number(process.versions.node.split(".")[0]),n=new Date("2025-04-30T00:00:00.000Z"),o=n<=new Date,i=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new P(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&o)throw new P(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(Qp.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${i}. please upgrade to a newer Node.js version.`))}async function vR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(B(),J)),Promise.resolve().then(()=>(Of(),_f))]);N("Starting Testim.io CLI"),rf(ql);try{wR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await D.fetch();let t=await e.process();if(N("in main, after options.process"),pc(global.proxyUri),CT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,uc(t.project),mm("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(bn(),Nf));return await o()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Yr(),await dn(t);let{preloadTests:o}=await Promise.resolve().then(()=>(ii(),Ff));await o(t),!t.playerRequirePath&&t.mode!==q.EXTENSION&&await br(t.playerLocation,t.canary);let i=await pm();i.success?console.log(`created prefetched data at ${Po()}`):console.error("failed to create prefetch data",i.error);return}let r=await Promise.resolve().then(()=>(iT(),oT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:o}=await Promise.resolve().then(()=>(hu(),gu));await o(t);return}if(s.isAgentMode(t)){let{runAgentMode:o}=await Promise.resolve().then(()=>(Jp(),AT));return o(t)}if(t.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(ju(),Qg)),{port:i}=await o(t);t.localRCASaver=`http://localhost:${i}`}t.exitCodeIgnoreFailingTests&&af(),N("right before testRunner.init/prepareRunner.prepare");let[n]=await Promise.all([Zm(t),r.init(t)]);return N("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof jr)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Ol({...r,error:t.message}).catch(()=>{}),t instanceof P?(console.log(Qp.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),TR.error("runner ended with unexpected error",{err:t}),t)}}vR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),ql(s)});
|
|
421
421
|
//# sourceMappingURL=cli.js.map
|