@testim/testim-cli 4.134.0 → 4.135.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 +52 -52
- package/cli.js.map +4 -4
- package/npm-shrinkwrap.json +401 -1345
- package/package.json +3 -4
package/cli.js
CHANGED
|
@@ -1,53 +1,53 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var OT=Object.create;var
|
|
3
|
-
${c.msg}`));for(let u of VT)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(o&&!m&&(c.msg=o),d.text=c),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Se.CoralogixLogger.configure(t),Br.options=t}}});var gc={};H(gc,{getLogger:()=>x,sessionPlayerLoggerFormatter:()=>pc,setExecutionId:()=>dc,setProjectId:()=>mc,setProxyUri:()=>fc});function qT(){let s=[],e=()=>Promise.resolve();if(!We){let{CoralogixTransport:t}=(cc(),Me(ac));t.configure(Nd);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}if(fd){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} ${fi.inspect(r.meta,t)}`))}))}return[s,e]}function dc(s){lc=s}function mc(s){Ud=s}function fc(s){if(We||!s)return;let{CoralogixTransport:e}=(cc(),Me(ac));e.configure({...Nd,proxyUri:s})}function Ld(s){return{projectId:Ud,time:new Date().toISOString(),...lc&&!s&&{executionId:lc}}}function x(s){return new uc(XT.child({category:s}))}var Dd,dt,fi,mi,Md,GT,HT,Nd,Od,pc,zT,KT,JT,YT,XT,lc,Ud,uc,W=v(()=>{"use strict";Dd=I(require("os")),dt=I(require("winston"));de();fi=I(require("util")),mi=I(require("chalk")),Md=I(require("dayjs"));F();GT=Dd.hostname(),HT=ze(),Nd={privateKey:kd,applicationName:"testim",subsystemName:"runner"};Od={depth:5,colors:!0},pc=(s,e,t)=>{let r=`[${(0,Md.default)().format("HH:mm:ss:SSS")}]`,n=fi.inspect(e,Od),i=fi.inspect(t,Od);return`${mi.default.white(r)} ${mi.default.reset()}SessionPlayer-${mi.default.red(s)} ${n} ${i}`},[zT,KT]=qT(),JT=gd?"debug":"info",YT={release:Boolean(!0),branch:"production"},XT=dt.createLogger({levels:dt.config.syslog.levels,level:JT,transports:zT,defaultMeta:{name:"runner",hostname:GT,nodeVersion:process.version,runnerVersion:HT,...YT}}),lc=null,Ud=null;uc=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,...Ld(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Ld(n)})}catch{}}}waitForFlush(){return KT()}}});var bi,jr,C,Ht,ur,St,gi,$r,ie,Ns,tt,qt,It,hi,Wr,yi,Us,Y=v(()=>{"use strict";bi=require("p-retry"),jr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Ht=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},ur=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},St=class extends bi.AbortError{},gi=class extends bi.AbortError{},$r=class extends bi.AbortError{},ie=class extends Error{},Ns=class extends Error{},tt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},qt=class extends tt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},It=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},hi=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}},yi=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Us=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function hc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ae(s){return(0,jd.setTimeout)(s)}function yc(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"){ui&&!Fd&&(Fd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ie(t);return e=ui?Number(ui)||6e5:e,Promise.race([s,ae(e).then(()=>{throw r})])}async function oe(s,e,{concurrency:t}={}){if(t){Bd||=(await import("p-limit")).default;let r=Bd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function zt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var jd,Fd,Bd,bc=v(()=>{"use strict";jd=require("timers/promises");Y();de();Fd=!1});var Bs,$d,QT,Fs,Wd,ZT,ew,Vd,Gd=v(()=>{"use strict";Bs=I(require("lodash"));de();$d=require("dns");W();bc();QT=x("http-request-counters"),Fs=!1,Wd=async()=>{if(We)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await oe(s,t=>$d.promises.lookup(t)));return e||(Fs=!0),e}catch{return QT.error("network connectivity test failed"),Fs=!0,!1}},ZT=Bs.throttle(Wd,10*1e3),ew=60*1e3*15,Vd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},ew)}function t(n,i=n.name){return async function(...o){e(s.call,i);try{let a=await n.call(null,...o);return e(s.success,i),a}catch(a){throw e(s.fail,i),Fs||ZT(),a}}}async function r(){if(Fs||!await Wd())return!1;let n=Bs.sum([...s.fail.values()]),i=Bs.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Fs,t}});var Ke={};H(Ke,{deleteReq:()=>js,didNetworkConnectivityTestFail:()=>Rc,download:()=>Sc,get:()=>be,getFullRes:()=>iw,getText:()=>Ws,head:()=>ow,isNetworkHealthy:()=>Ic,post:()=>Ve,postForm:()=>$s,postText:()=>vc,put:()=>Ec});function rw(){return global.caFileContent}function sw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function nw(){return!mt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(mt.default),global.proxyUri}function pr(s,e=!1){let t=rw();t&&s.ca(t);let r=!e&&nw();r&&s.proxy(r)}async function Hd(s,e,t={},r=Vr,n=0){let i=mt.default.post(s).send(e).timeout(r).set(t);pr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function wc(s,e,t={},r=Vr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=mt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),pr(o,i),await o}var mt,Tc,rt,Vr,tw,Dt,js,Ve,$s,Ws,vc,be,iw,ow,Ec,Sc,Ic,Rc,Ge=v(()=>{"use strict";mt=I(require("superagent"));W();Gd();Tc=x("http-request"),rt=Vd(),Vr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,tw=6e4;Dt=(s,e,t)=>{let r=e.response;e.response instanceof mt.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw Tc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};js=rt(async(s,e={},t={},r=Vr)=>{try{let n=mt.default.delete(s).send(e).timeout(r).set(t);pr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Dt("failed to delete request",n,{url:s})}}),Ve=rt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await Hd(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});$s=rt(async(s,e,t,r={},n=Vr)=>{let i=mt.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),pr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});Ws=rt(async(s,e,t)=>{try{return(await wc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),vc=rt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Hd(s,e,t,r,n)).text}catch(i){return Dt("failed to post request",i,{url:s})}}),be=rt(async(s,e,t,r,n)=>{try{return(await wc(s,e,t,r,n)).body}catch(i){return Dt("failed to get request",i,{url:s,query:e})}}),iw=rt((s,e,t,r)=>wc(s,e,t,r)),ow=rt(async s=>{let e=mt.default.head(s).timeout(Vr);pr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),Ec=rt(async(s,e,t={},r=Vr)=>{let n=mt.default.put(s).send(e).timeout(r).set(t);pr(n);try{return(await n).body}catch(i){return Dt("failed to put request",i,{url:s})}}),Sc=rt(async s=>{Tc.info("start to download",{url:s});let e=mt.default.get(s).timeout(tw).buffer(!0).parse(sw);pr(e);try{let t=await e;return Tc.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),Ic=rt.isNetworkHealthy,Rc=rt.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 Ti(s,e){return _e(s)?e||Mt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Mt.basename(s)}function ze(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function xc(){try{return ld.node}catch{return""}}async function Kd(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 i=Mt.join(s,n.name),o=Mt.join(e,n.name);n.isDirectory()?await Kd(i,o):await st.promises.copyFile(i,o)}}async function he(s){try{return await st.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Mt,qd,zd,st,aw,Nt,Je,wi,Ac,nt,Cc,Jd=v(()=>{"use strict";Mt=I(require("path"));Qa();li();qd=I(require("unzip-stream")),zd=I(require("p-retry")),st=require("fs"),aw=3;Nt=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Ke));return(0,zd.default)(()=>e.download(s),{retries:aw,factor:1})},Je=async(s,e)=>{let t=await Nt(s);return st.promises.writeFile(e,t.body)};wi=async(s,e)=>{let t=Ti(s,e);return _e(s)?Je(s,t):st.promises.copyFile(s,t)},Ac=async s=>_e(s)?Nt(s):st.promises.readFile(s),nt=async(s,e)=>await(0,st.createReadStream)(s).pipe(qd.Extract({path:e})),Cc=s=>(0,st.statSync)(s).size/1e6});var Ut={};H(Ut,{APPIUM_SESSION_MESSAGE:()=>Lc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>vi,MOBILE_RUN_SKIP_REASON:()=>Oc,gridMessages:()=>gt,gridTypes:()=>L,mobileWeb:()=>kc,runnerStatus:()=>Pc,runnerTestStatus:()=>me,socketEventTypes:()=>Rt,stepResult:()=>Gs,test:()=>_c,testRunStatus:()=>Vs,testStatus:()=>Ye,timeoutMessages:()=>Ue});var Ue,Vs,Pc,me,Ye,gt,kc,_c,Rt,q,L,Gs,vi,Oc,Lc,ne=v(()=>{"use strict";Ue={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Vs={COMPLETED:"completed"},Pc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},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"},kc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},_c={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Rt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},L={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",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"},Gs={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"},vi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Oc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Lc={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 Hs(s,e){var t,r,n;return(t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(i=>{var o;return(o=i.runConfig)==null?void 0:o.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function cw(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var qs,Yd,Xe,lw,uw,pw,dw,mw,Dc,Mc,Xd=v(()=>{"use strict";ne();qs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},Yd=s=>Boolean(s.resultId&&s.source==="remote-run"),Xe=(s,e)=>s.testStatus===Ye.QUARANTINE&&!Yd(e)&&!e.runQuarantinedTests;lw=s=>Boolean(s.loginMode),uw=s=>Boolean(s.tunnelOnlyMode),pw=s=>Boolean(s.createPrefechedData),dw=s=>Boolean(s.installLazyDepsMode),mw=s=>Boolean(s.agentMode),Dc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Mc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Si(s=0){return Ei.default.duration(s).format("HH:mm:ss.SSS")}function Nc(s=0){return Ei.default.duration(s).asSeconds()}var Ei,Qd,Zd=v(()=>{"use strict";Ei=I(require("dayjs")),Qd=I(require("dayjs/plugin/duration"));Ei.default.extend(Qd.default)});var zs,Gr,Kt,em,Hr,tm=v(()=>{"use strict";ne();zs=s=>!(!s||"fileName"in s),Gr=(s,e)=>{if(e===L.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Kt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},em=s=>s===L.TESTIM_TVC,Hr=(s,e)=>em(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Uc(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 rm=v(()=>{"use strict"});var J={};H(J,{OSS:()=>qr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>Xa,calcPercentile:()=>Ai,copyDir:()=>Kd,delay:()=>ae,doesPathExist:()=>he,download:()=>Nt,downloadAndSave:()=>Je,extractElementId:()=>Oe,getArgsOnRemoteRunFailure:()=>cw,getBrowserInfo:()=>gw,getCdpAddressForHost:()=>fr,getCliLocation:()=>ft,getDuration:()=>Si,getDurationSec:()=>Nc,getEnginesVersion:()=>xc,getEnvironmentGitBranch:()=>mr,getLinksFromUnescapeHTML:()=>Ys,getLocalFileSizeInMB:()=>Cc,getMemorySnapshot:()=>Uc,getPlanType:()=>Ri,getRunConfigByBrowserName:()=>Ks,getRunnerVersion:()=>ze,getSource:()=>wi,getSourceAsBuffer:()=>Ac,getSourcePath:()=>Ti,getTestUrl:()=>qe,getUniqBrowsers:()=>Hs,groupTestsByRetries:()=>Bc,guid:()=>re,hasTestPlanFlag:()=>qs,isAgentMode:()=>mw,isAppFromDevice:()=>zs,isAppFromDeviceDisabled:()=>Hr,isCreatePrefetchedDataMode:()=>pw,isInstallLazyDepsMode:()=>dw,isLoginMode:()=>lw,isMobileProject:()=>Kt,isPromise:()=>hc,isQuarantineAndNotRemoteRun:()=>Xe,isRemoteRun:()=>Yd,isTestimVirtualGrid:()=>em,isTunnelOnlyMode:()=>uw,isURL:()=>_e,promiseAbort:()=>yc,promiseFromCallback:()=>zt,promiseMap:()=>oe,promiseTimeout:()=>ce,removePropertyFromObject:()=>Ii,replaceArgsWithNoDashes:()=>Dc,sanitizeNumberValue:()=>dr,shouldBlockVirtualIosBuild:()=>Gr,spreadObjectToArgs:()=>Mc,unescapeHTML:()=>Js,unzipFile:()=>nt});function dr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function gw(s){return s=s.toLowerCase(),Fc.find(e=>e.browserValue===s)}function Ks(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Fc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Fc[0],n=qr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=qr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=qr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=qr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=qr.find(i=>i.bs.platform===t.platform))),zr.merge(r,n)}function mr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Ii(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Ii(s[r],e,t))}function Oe(s){return s.ELEMENT||s[Gt]}function Ri(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Bc(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((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=zr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Js(s){return om.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Ys(s){return[...om.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function fr(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 sm,zr,nm,im,fw,Ft,qr,Fc,Ai,om,F=v(()=>{"use strict";sm=I(require("os")),zr=I(require("lodash")),nm=I(require("path")),im=require("linkedom");Fr();Jd();Xd();Zd();Qa();bc();tm();rm();fw=sm.homedir(),Ft=nm.join(fw,".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"}}],Fc=[{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"}];Ai=(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]};om=new im.DOMParser});var jc={};H(jc,{$schema:()=>hw,default:()=>vw,definitions:()=>yw,properties:()=>ww,required:()=>Tw,type:()=>bw});var hw,yw,bw,Tw,ww,vw,am=v(()=>{hw="http://json-schema.org/draft-07/schema#",yw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},bw="object",Tw=["entries"],ww={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},vw={$schema:hw,definitions:yw,type:bw,required:Tw,properties:ww}});async function fm(){try{return await ce(Ci.promises.readFile(_i()).then(async s=>{let e=await mm;return Iw(e,s)}),3e4)}catch{return{}}}function Iw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=Jr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Bt(s,e,t=Ew,r=void 0){return async()=>{if(!um)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Rw(e);if(i)return Xs.debug("cache hit:",{fnName:e}),i;if(Xs.debug("cache miss:",{fnName:e}),!pm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Aw(e,o,t),o}}async function Rw(s){let t=(await Oi)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Aw(s,e,t){if($c)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 Oi;r[s]={value:e,expiry:Date.now()+t},dm=new Promise(n=>{ki=n}),Sw(r)}catch{Xs.error("failed updating cache")}}async function Yr(){let s=await Oi;Object.keys(s).forEach(e=>{delete s[e]})}function gm(s){um=s}function Cw(s=!0){pm=s}async function hm(){try{return $c=!0,await dm}finally{$c=!1}}function ym(s){Pi=s,Oi=fm()}var Ci,xi,Jr,cm,Xs,Pi,lm,ki,um,pm,$c,dm,mm,Ew,_i,Oi,Sw,bm,Tm,eA,wm,Jt=v(()=>{"use strict";Ci=I(require("fs")),xi=I(require("path")),Jr=I(require("crypto"));F();cm=require("lodash");W();Xs=x("local cache"),Pi=xi.resolve(ft(),"testim-cache"),um=!0,pm=!0,$c=!1,dm=new Promise(s=>{ki=s}),mm=new Promise(s=>{lm=s}),Ew=1e3*60*60*3,_i=()=>xi.resolve(xi.resolve(Pi,"testim.cache"));Oi=fm(),Sw=(0,cm.debounce)(async s=>{let e;try{let t=await mm,r=Jr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=Jr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await he(Pi)||await Ci.promises.mkdir(Pi,{recursive:!0}),await Ci.promises.writeFile(_i(),a)}catch(t){Xs.error("failed saving cache",{err:t}),e=t}ki(e?{success:!1,error:e}:{success:!0})},200);bm=lm,Tm=gm.bind(void 0,!1),eA=gm.bind(void 0,!0),wm=()=>Cw(!1)});function Li(){return{cliLocation:ft(),userInfo:Xr.userInfo(),platform:Xr.platform(),release:Xr.release()}}var Xr,Wc=v(()=>{"use strict";Xr=I(require("os"));F()});function xw(s){try{return Di.resolve(Di.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 Yt(s){let e=xw(s);return require(e)}var Di,Qs=v(()=>{"use strict";Di=I(require("path"))});function Pw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function kw(s){return/The "to" argument must be of type string./.exec(s)}function Im(s,e,t){let r=Pw(s),n=kw(s);return r||n?(Sm.info("Failed to install package due to insufficient write access",{...Li(),package:t,path:r}),console.error(`
|
|
2
|
+
"use strict";var OT=Object.create;var Zn=Object.defineProperty;var LT=Object.getOwnPropertyDescriptor;var DT=Object.getOwnPropertyNames;var MT=Object.getPrototypeOf,NT=Object.prototype.hasOwnProperty;var w=(s,e)=>()=>(s&&(e=s(s=0)),e);var H=(s,e)=>{for(var t in e)Zn(s,t,{get:e[t],enumerable:!0})},sd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of DT(e))!NT.call(s,n)&&n!==t&&Zn(s,n,{get:()=>e[n],enumerable:!(r=LT(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?OT(MT(s)):{},sd(e||!s||!s.__esModule?Zn(t,"default",{value:s,enumerable:!0}):t,s)),Fe=s=>sd(Zn({},"__esModule",{value:!0}),s);var Be={};H(Be,{log:()=>U,measure:()=>FT});function U(...s){if(!id)return;let e=Date.now();console.log(`${e-UT} ${e-nd} `,...s),nd=e}function FT(s,e){if(!id)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var id,UT,nd,je=w(()=>{"use strict";id=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,UT=Date.now(),nd=Date.now()});var Vt,Ur=w(()=>{"use strict";Vt="element-6066-11e4-a52e-4f735466cecf"});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function He(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function Ya(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 Xa=w(()=>{"use strict"});var Za,od,ad,ai=w(()=>{Za={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":"2.1.3","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.3",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",express:"4.21.1",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"1.1.4",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"4.9.18",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.8.0","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"7.0.0","ua-parser-js":"0.7.39","unzip-stream":"0.3.4","validate-npm-package-name":"3.0.0",webdriverio:"8.40.6",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},ad={node:">= 18.0.0"}});var ks,$T,cd,ld,ud,ci,_s,pd,fe,dd,md,li,$e,ec,fd,ui,gd,xR,CR,hd,yd,Os,bd,Td,wd,vd,tc,rc,sc,nc,Ed,Ls,Sd,ic,Id,Rd,Ad,xd,PR,de=w(()=>{"use strict";ks=process.env.SERVICES_HOST||"https://services.testim.io",$T="https://testimstatic.blob.core.windows.net",cd="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:ks,ks=process.env.SERVICES_HOST);ld=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),ud=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),ci=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),_s=process.env.EDITOR_URL,pd=process.env.WEBSOCKET_HOST||`${ks}/ws`,fe=ks,dd=parseInt(process.env.LOGGER_CONSOLE||"0",10),md=parseInt(process.env.LOGGER_DEBUG||"0",10),li=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),$e=parseInt(process.env.IS_ON_PREM||"0",10),ec=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,fd=parseInt(process.env.DEBUG_MODE||"0",10),ui=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,gd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",xR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),CR=process.env.APPIUM_VERSION||"1.10.1",hd=process.env.GATEWAY_URL,yd=process.env.EXTENSION_SERVICES_HOST||ks,Os=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:$T,bd=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:cd,Td=cd,wd=5*60*1e3,vd=40,tc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",rc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",sc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",nc=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Ed=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Ls=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Sd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,ic=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung",Id=process.env.TEST_RESULT_ARTIFACTS_BUCKET||"test-result-artifacts",Rd=process.env.CLI_AGENT_GOOGLE_API_KEY,Ad=process.env.CLI_AGENT_GOOGLE_CLIENT_ID,xd=process.env.CLI_AGENT_GOOGLE_CLIENT_SECRET,PR=process.env.CORALOGIX_PRIVATE_KEY});var Cd,pi,Pd=w(()=>{"use strict";Cd=I(require("superagent")),pi=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=process.env.CORALOGIX_PRIVATE_KEY||"",this.applicationName=e.applicationName,this.subsystemName=e.subsystemName,this.flushIntervalMs=e.flushIntervalMs||2e3,this.maxBufferedLogsCount=e.maxBufferedLogsCount||50,this.interval=setInterval(()=>this.flushLogs(),this.flushIntervalMs)}addLog(e){this.logs.push(e),this.logs.length>=this.maxBufferedLogsCount&&this.flushLogs()}setProxy(e){this.proxy=e}async waitForFlush(){clearInterval(this.interval),await this.flushLogs()}async flushLogs(){try{if(this.logs.length===0)return;let e={applicationName:this.applicationName,subsystemName:this.subsystemName,logEntries:[...this.logs]};this.logs=[];let t=Cd.default.post(this.url).set("Content-Type","application/json; charset=UTF-8").set("Authorization",`Bearer ${this.token}`).send(e);this.proxy&&t.proxy(this.proxy),await t}catch{}}}});var _d={};H(_d,{CoralogixTransport:()=>oc});var kd,WT,VT,oc,Od=w(()=>{"use strict";kd=I(require("winston-transport"));Pd();WT={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},VT=["err","error","reason","e"],oc=class extends kd.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new pi({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...l}=t,c={...a,...l},d={severity:WT[i],text:o,category:n||this.category};c.className&&(d.className=c.className),c.methodName&&(d.methodName=c.methodName),c.threadId&&(d.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let m=!1;a instanceof Error&&(m=!0,c.msg=a.message+a.stack,o&&(c.msg=`${o}
|
|
3
|
+
${c.msg}`));for(let u of VT)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(o&&!m&&(c.msg=o),d.text=JSON.stringify(c)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});var mc={};H(mc,{getLogger:()=>C,sessionPlayerLoggerFormatter:()=>lc,setExecutionId:()=>uc,setProjectId:()=>pc,setProxyUri:()=>dc});function qT(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!$e){let{CoralogixTransport:r}=(Od(),Fe(_d)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(dd){let r={depth:5,colors:!0};s.push(new pt.transports.Console({format:pt.format.combine(pt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),pt.format.timestamp({format:"HH:mm:ss:SSS"}),pt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${mi.inspect(n.meta,r)}`))}))}return[s,e,t]}function uc(s){ac=s}function pc(s){Ud=s}function dc(s){$e||!s||JT(s)}function Dd(s){return{projectId:Ud,time:new Date().toISOString(),...ac&&!s&&{executionId:ac}}}function C(s){return new cc(QT.child({category:s}))}var Md,pt,mi,di,Nd,GT,HT,Ld,lc,zT,KT,JT,YT,XT,QT,ac,Ud,cc,W=w(()=>{"use strict";Md=I(require("node:os")),pt=I(require("winston"));de();mi=I(require("node:util")),di=I(require("chalk")),Nd=I(require("dayjs"));F();GT=Md.hostname(),HT=qe();Ld={depth:5,colors:!0},lc=(s,e,t)=>{let r=`[${(0,Nd.default)().format("HH:mm:ss:SSS")}]`,n=mi.inspect(e,Ld),i=mi.inspect(t,Ld);return`${di.default.white(r)} ${di.default.reset()}SessionPlayer-${di.default.red(s)} ${n} ${i}`},[zT,KT,JT]=qT(),YT=md?"debug":"info",XT={release:Boolean(!0),branch:"production"},QT=pt.createLogger({levels:pt.config.syslog.levels,level:YT,transports:zT,defaultMeta:{name:"runner",hostname:GT,nodeVersion:process.version,runnerVersion:HT,...XT}}),ac=null,Ud=null;cc=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,...Dd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Dd(n)})}catch{}}}waitForFlush(){return KT()}}});var yi,Fr,x,Gt,lr,Et,fi,Br,ie,Ds,et,Ht,St,gi,jr,hi,Ms,Y=w(()=>{"use strict";yi=require("p-retry"),Fr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},x=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Gt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},lr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},Et=class extends yi.AbortError{},fi=class extends yi.AbortError{},Br=class extends yi.AbortError{},ie=class extends Error{},Ds=class extends Error{},et=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Ht=class extends et{constructor(){super(...arguments);this.name="GridConcurrencyError"}},St=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},gi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},jr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},hi=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Ms=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function fc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ae(s){return(0,jd.setTimeout)(s)}function gc(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"){ci&&!Fd&&(Fd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ie(t);return e=ci?Number(ci)||6e5:e,Promise.race([s,ae(e).then(()=>{throw r})])}async function oe(s,e,{concurrency:t}={}){if(t){Bd||=(await import("p-limit")).default;let r=Bd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function qt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var jd,Fd,Bd,hc=w(()=>{"use strict";jd=require("timers/promises");Y();de();Fd=!1});var Us,$d,ZT,Ns,Wd,ew,tw,Vd,Gd=w(()=>{"use strict";Us=I(require("lodash"));de();$d=require("dns");W();hc();ZT=C("http-request-counters"),Ns=!1,Wd=async()=>{if($e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await oe(s,t=>$d.promises.lookup(t)));return e||(Ns=!0),e}catch{return ZT.error("network connectivity test failed"),Ns=!0,!1}},ew=Us.throttle(Wd,10*1e3),tw=60*1e3*15,Vd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},tw)}function t(n,i=n.name){return async function(...o){e(s.call,i);try{let a=await n.call(null,...o);return e(s.success,i),a}catch(a){throw e(s.fail,i),Ns||ew(),a}}}async function r(){if(Ns||!await Wd())return!1;let n=Us.sum([...s.fail.values()]),i=Us.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Ns,t}});var ze={};H(ze,{deleteReq:()=>Fs,didNetworkConnectivityTestFail:()=>Sc,download:()=>vc,get:()=>be,getFullRes:()=>ow,getText:()=>js,head:()=>aw,isNetworkHealthy:()=>Ec,post:()=>We,postForm:()=>Bs,postText:()=>Tc,put:()=>wc});function sw(){return global.caFileContent}function nw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function iw(){return!dt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(dt.default),global.proxyUri}function ur(s,e=!1){let t=sw();t&&s.ca(t);let r=!e&&iw();r&&s.proxy(r)}async function Hd(s,e,t={},r=$r,n=0){let i=dt.default.post(s).send(e).timeout(r).set(t);ur(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function bc(s,e,t={},r=$r,{isBinary:n=!1,skipProxy:i=!1}={}){let o=dt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),ur(o,i),await o}var dt,yc,tt,$r,rw,Lt,Fs,We,Bs,js,Tc,be,ow,aw,wc,vc,Ec,Sc,Ve=w(()=>{"use strict";dt=I(require("superagent"));W();Gd();yc=C("http-request"),tt=Vd(),$r=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,rw=6e4;Lt=(s,e,t)=>{let r=e.response;e.response instanceof dt.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw yc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Fs=tt(async(s,e={},t={},r=$r)=>{try{let n=dt.default.delete(s).send(e).timeout(r).set(t);ur(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Lt("failed to delete request",n,{url:s})}}),We=tt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await Hd(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Lt("failed to post request",i,{url:s})}});Bs=tt(async(s,e,t,r={},n=$r)=>{let i=dt.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),ur(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Lt("failed to post request",o,{url:s})}});js=tt(async(s,e,t)=>{try{return(await bc(s,e,t)).text}catch(r){return Lt("failed to getText request",r,{url:s,query:e})}}),Tc=tt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Hd(s,e,t,r,n)).text}catch(i){return Lt("failed to post request",i,{url:s})}}),be=tt(async(s,e,t,r,n)=>{try{return(await bc(s,e,t,r,n)).body}catch(i){return Lt("failed to get request",i,{url:s,query:e})}}),ow=tt((s,e,t,r)=>bc(s,e,t,r)),aw=tt(async s=>{let e=dt.default.head(s).timeout($r);ur(e);try{return await e}catch(t){return Lt("failed to head request",t,{url:s})}}),wc=tt(async(s,e,t={},r=$r)=>{let n=dt.default.put(s).send(e).timeout(r).set(t);ur(n);try{return(await n).body}catch(i){return Lt("failed to put request",i,{url:s})}}),vc=tt(async s=>{yc.info("start to download",{url:s});let e=dt.default.get(s).timeout(rw).buffer(!0).parse(nw);ur(e);try{let t=await e;return yc.info("finished to download",{url:s}),t}catch(t){return Lt("failed to download",t,{url:s})}}),Ec=tt.isNetworkHealthy,Sc=tt.didNetworkConnectivityTestFail});function mt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Dt.resolve(__dirname,"../../"):s=Dt.resolve(__dirname,""),s):process.cwd()}function bi(s,e){return ke(s)?e||Dt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Dt.basename(s)}function qe(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Ac(){try{return ad.node}catch{return""}}async function Kd(s,e,t=!0){let r=await rt.promises.readdir(s,{withFileTypes:!0});await rt.promises.mkdir(e,{recursive:t});for(let n of r){let i=Dt.join(s,n.name),o=Dt.join(e,n.name);n.isDirectory()?await Kd(i,o):await rt.promises.copyFile(i,o)}}async function he(s){try{return await rt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Dt,qd,zd,rt,cw,Mt,Ke,Ti,Ic,st,Rc,Jd=w(()=>{"use strict";Dt=I(require("path"));Xa();ai();qd=I(require("unzip-stream")),zd=I(require("p-retry")),rt=require("fs"),cw=3;Mt=async s=>{let e=await Promise.resolve().then(()=>(Ve(),ze));return(0,zd.default)(()=>e.download(s),{retries:cw,factor:1})},Ke=async(s,e)=>{let t=await Mt(s);return rt.promises.writeFile(e,t.body)};Ti=async(s,e)=>{let t=bi(s,e);return ke(s)?Ke(s,t):rt.promises.copyFile(s,t)},Ic=async s=>ke(s)?Mt(s):rt.promises.readFile(s),st=async(s,e)=>await(0,rt.createReadStream)(s).pipe(qd.Extract({path:e})),Rc=s=>(0,rt.statSync)(s).size/1e6});var Nt={};H(Nt,{APPIUM_SESSION_MESSAGE:()=>_c,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>wi,MOBILE_RUN_SKIP_REASON:()=>kc,gridMessages:()=>ft,gridTypes:()=>L,mobileWeb:()=>Cc,runnerStatus:()=>xc,runnerTestStatus:()=>me,socketEventTypes:()=>It,stepResult:()=>Ws,test:()=>Pc,testRunStatus:()=>$s,testStatus:()=>Je,timeoutMessages:()=>Me});var Me,$s,xc,me,Je,ft,Cc,Pc,It,q,L,Ws,wi,kc,_c,ne=w(()=>{"use strict";Me={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},$s={COMPLETED:"completed"},xc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Je={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ft={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Cc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Pc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},It={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},L={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",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"},Ws={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"},wi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},kc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},_c={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 Vs(s,e){var t,r,n;return(t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(i=>{var o;return(o=i.runConfig)==null?void 0:o.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function 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 Gs,Yd,Ye,uw,pw,dw,mw,fw,Oc,Lc,Xd=w(()=>{"use strict";ne();Gs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},Yd=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Je.QUARANTINE&&!Yd(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),Oc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Lc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Ei(s=0){return vi.default.duration(s).format("HH:mm:ss.SSS")}function Dc(s=0){return vi.default.duration(s).asSeconds()}var vi,Qd,Zd=w(()=>{"use strict";vi=I(require("dayjs")),Qd=I(require("dayjs/plugin/duration"));vi.default.extend(Qd.default)});var Hs,Wr,zt,em,Vr,tm=w(()=>{"use strict";ne();Hs=s=>!(!s||"fileName"in s),Wr=(s,e)=>{if(e===L.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},zt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},em=s=>s===L.TESTIM_TVC,Vr=(s,e)=>em(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Mc(s=4e3){let e=process.memoryUsage(),t=r=>Math.round(r/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>s,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var rm=w(()=>{"use strict"});var J={};H(J,{OSS:()=>Gr,TESTIM_BROWSER_DIR:()=>Ut,buildBasicHeader:()=>Ya,calcPercentile:()=>Ri,copyDir:()=>Kd,delay:()=>ae,doesPathExist:()=>he,download:()=>Mt,downloadAndSave:()=>Ke,extractElementId:()=>_e,getArgsOnRemoteRunFailure:()=>lw,getBrowserInfo:()=>hw,getCdpAddressForHost:()=>mr,getCliLocation:()=>mt,getDuration:()=>Ei,getDurationSec:()=>Dc,getEnginesVersion:()=>Ac,getEnvironmentGitBranch:()=>dr,getLinksFromUnescapeHTML:()=>Ks,getLocalFileSizeInMB:()=>Rc,getMemorySnapshot:()=>Mc,getPlanType:()=>Ii,getRunConfigByBrowserName:()=>qs,getRunnerVersion:()=>qe,getSource:()=>Ti,getSourceAsBuffer:()=>Ic,getSourcePath:()=>bi,getTestUrl:()=>He,getUniqBrowsers:()=>Vs,groupTestsByRetries:()=>Uc,guid:()=>re,hasTestPlanFlag:()=>Gs,isAgentMode:()=>fw,isAppFromDevice:()=>Hs,isAppFromDeviceDisabled:()=>Vr,isCreatePrefetchedDataMode:()=>dw,isInstallLazyDepsMode:()=>mw,isLoginMode:()=>uw,isMobileProject:()=>zt,isPromise:()=>fc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>Yd,isTestimVirtualGrid:()=>em,isTunnelOnlyMode:()=>pw,isURL:()=>ke,promiseAbort:()=>gc,promiseFromCallback:()=>qt,promiseMap:()=>oe,promiseTimeout:()=>ce,removePropertyFromObject:()=>Si,replaceArgsWithNoDashes:()=>Oc,sanitizeNumberValue:()=>pr,shouldBlockVirtualIosBuild:()=>Wr,spreadObjectToArgs:()=>Lc,unescapeHTML:()=>zs,unzipFile:()=>st});function pr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function hw(s){return s=s.toLowerCase(),Nc.find(e=>e.browserValue===s)}function qs(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Nc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Nc[0],n=Gr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=Gr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=Gr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=Gr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=Gr.find(i=>i.bs.platform===t.platform))),Hr.merge(r,n)}function dr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Si(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Si(s[r],e,t))}function _e(s){return s.ELEMENT||s[Vt]}function Ii(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Uc(s=[]){return Hr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=Hr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function zs(s){return om.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Ks(s){return[...om.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function mr(s,e){let t=await Promise.resolve().then(()=>(Ve(),ze));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var sm,Hr,nm,im,gw,Ut,Gr,Nc,Ri,om,F=w(()=>{"use strict";sm=I(require("os")),Hr=I(require("lodash")),nm=I(require("path")),im=require("linkedom");Ur();Jd();Xd();Zd();Xa();hc();tm();rm();gw=sm.homedir(),Ut=nm.join(gw,".testim-browser-profile"),Gr=[{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"}}],Nc=[{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"}];Ri=(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]};om=new im.DOMParser});var Fc={};H(Fc,{$schema:()=>yw,default:()=>Ew,definitions:()=>bw,properties:()=>vw,required:()=>ww,type:()=>Tw});var yw,bw,Tw,ww,vw,Ew,am=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"}}},Ew={$schema:yw,definitions:bw,type:Tw,required:ww,properties:vw}});async function fm(){try{return await ce(Ai.promises.readFile(ki()).then(async s=>{let e=await mm;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),i=zr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Ft(s,e,t=Sw,r=void 0){return async()=>{if(!um)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Aw(e);if(i)return Js.debug("cache hit:",{fnName:e}),i;if(Js.debug("cache miss:",{fnName:e}),!pm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await xw(e,o,t),o}}async function Aw(s){let t=(await _i)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function xw(s,e,t){if(Bc)throw Js.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 _i;r[s]={value:e,expiry:Date.now()+t},dm=new Promise(n=>{Pi=n}),Iw(r)}catch{Js.error("failed updating cache")}}async function Kr(){let s=await _i;Object.keys(s).forEach(e=>{delete s[e]})}function gm(s){um=s}function Cw(s=!0){pm=s}async function hm(){try{return Bc=!0,await dm}finally{Bc=!1}}function ym(s){Ci=s,_i=fm()}var Ai,xi,zr,cm,Js,Ci,lm,Pi,um,pm,Bc,dm,mm,Sw,ki,_i,Iw,bm,Tm,iA,wm,Kt=w(()=>{"use strict";Ai=I(require("fs")),xi=I(require("path")),zr=I(require("crypto"));F();cm=require("lodash");W();Js=C("local cache"),Ci=xi.resolve(mt(),"testim-cache"),um=!0,pm=!0,Bc=!1,dm=new Promise(s=>{Pi=s}),mm=new Promise(s=>{lm=s}),Sw=1e3*60*60*3,ki=()=>xi.resolve(xi.resolve(Ci,"testim.cache"));_i=fm(),Iw=(0,cm.debounce)(async s=>{let e;try{let t=await mm,r=zr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=zr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await he(Ci)||await Ai.promises.mkdir(Ci,{recursive:!0}),await Ai.promises.writeFile(ki(),a)}catch(t){Js.error("failed saving cache",{err:t}),e=t}Pi(e?{success:!1,error:e}:{success:!0})},200);bm=lm,Tm=gm.bind(void 0,!1),iA=gm.bind(void 0,!0),wm=()=>Cw(!1)});function Oi(){return{cliLocation:mt(),userInfo:Jr.userInfo(),platform:Jr.platform(),release:Jr.release()}}var Jr,jc=w(()=>{"use strict";Jr=I(require("os"));F()});function Pw(s){try{return Li.resolve(Li.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 Jt(s){let e=Pw(s);return require(e)}var Li,Ys=w(()=>{"use strict";Li=I(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 Im(s,e,t){let r=kw(s),n=_w(s);return r||n?(Sm.info("Failed to install package due to insufficient write access",{...Oi(),package:t,path:r}),console.error(`
|
|
4
4
|
|
|
5
5
|
Testim failed installing the package ${t||""} due to insufficient permissions.
|
|
6
6
|
This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
|
|
7
7
|
Testim had missing write access to ${r||e}
|
|
8
8
|
|
|
9
|
-
`),!0):!1}function
|
|
10
|
-
stdout: ${l} stderr: ${c}`}Sm.info(`Npm Install closed with exit code ${u}`,{message:g,stderr:c}),i(new
|
|
9
|
+
`),!0):!1}function Vc(s){try{return Jt(s)}catch{return!1}}function Rm(s,e){return require(gr.join(s,`./node_modules/${e}/package.json`)).version}function Am(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=Am(s[e]);if(t)return t}}function xm(s){let e=require(gr.join(s,"package.json"));if(!("exports"in e))return"";let t=Am(e);if(!t)throw new hi(e.name);return t}async function Mi(s,e,t){let r=gr.join(s,"npm-shrinkwrap.json"),n=gr.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await he(r)&&(await Wc.promises.rename(r,n),i=!0)}catch{}return await Em(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw Im(o.stderr,s,e)?new jr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await Wc.promises.rename(n,r)}catch{}}}function Cm(s,e,t,r){return new Promise((n,i)=>{let o=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,Di.spawn)("node",[$c,"i","--prefix",s,...d,...e,...o],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`:Im(c,$c)?g=`insufficient write access in location ${$c}`: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}`}Sm.info(`Npm Install closed with exit code ${u}`,{message:g,stderr:c}),i(new St(g))}else n(l)}),setTimeout(()=>{try{m.kill()}finally{i(new ie)}},r)})}async function Pm(){try{return(await Em("npm -v")).stdout.trim()}catch{return""}}var Wc,gr,vm,Di,Em,Sm,$c,Yr=w(()=>{"use strict";Wc=I(require("fs")),gr=I(require("path"));F();vm=require("util"),Di=require("child_process");W();jc();Ys();Y();Em=(0,vm.promisify)(Di.exec),Sm=C("cli-service");$c=gr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var B,_m,Ow,Lw,Dw,km,Ni,Hc,O,le=w(()=>{"use strict";B=I(require("rox-node"));W();F();de();_m=C("FeatureFlagsService"),Ow=!$e&&!0&&!hd,Lw=2e4,Dw=60*60*24,km=["labs","disabled","enabled"],Ni=class extends B.default.Variant{constructor(e="disabled"){super(e,km)}getValue(){let e=super.getValue();return km.includes(e)?e:(_m.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Hc=class{constructor(){this.flags={useNewWSCLI:new B.default.Flag,useSafariWebdriverVisibilityChecks:new B.default.Flag,useClickimVisibilityChecks:new B.default.Flag,runGetElementCodeInAut:new B.default.Flag,enableFrameSwitchOptimization:new B.default.Flag,maximumJsResultSize:new B.default.Configuration(2e3*1024),skipFileInputClicks:new B.default.Flag,errorMessageOnBadNetwork:new B.default.Flag(!0),warnOnBadNetwork:new B.default.Flag(!1),overrideAzureStorageUrl:new B.default.Flag,autoSaveDownloadFileFireFox:new B.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new B.default.Flag(!0),experimentalPreCodeCompilation:new B.default.Flag(!0),experimentalAsyncCustomCode:new B.default.Flag,useSameBrowserForMultiTests:new Ni("labs"),highSpeedMode:new Ni,usePortedHtml5DragDrop:new B.default.Flag,testNamesToBeforeSuiteHook:new B.default.Flag,addCustomCapabilities:new B.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new B.default.Variant("{}"),LTNetworkCapabilities:new B.default.Flag,downloadToBase64:new B.default.Flag,publicGridURL:new B.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new B.default.Flag(!0),unsupportedCapsFields:new B.default.Variant("[]"),dontFocusOnInit:new B.default.Flag,retryOnSeleniumHubError:new B.default.Flag,enableLambdaTestTunnelNTLM:new B.default.Flag,enableLambdaTestTunnelSkipUpgrade:new B.default.Flag,tdcHsPreventNetworkCapture:new B.default.Flag,headSpinTdcEnableFlagCapability:new B.default.Flag,enableBatchTDC:new B.default.Flag,enableBatchHeadSpin:new B.default.Flag,clearRunnerFileCache:new B.default.Flag,forceTurboModeIfNeeded:new B.default.Flag,redisSlotManager:new B.default.Flag,tunnelBinaryNewVersion:new B.default.Flag(!1),encryptedCredentials:new B.default.Flag,computePackagePathFromPackageJsonExports:new B.default.Flag,sendExtensionOnEdgeNonLinux:new B.default.Flag,enableAppium2pCloudy:new B.default.Flag,reuseCliPkgInstallFolder:new B.default.Flag,getPublicIpFrom3rdPartyServices:new B.default.Flag,chromedriverCdnBinariesUrl:new B.default.Variant(""),sfdcHybridCompany:new B.default.Flag,allowFixingAppIdStructure:new B.default.Flag,enableAppium2BrowserStack:new B.default.Flag,increaseTDCRequestTimeout:new B.default.Flag,accessTokenExpiryMargin:new B.default.Configuration(300*1e3),useMV3Extension:new B.default.Flag,testimHeadlessExtensionDownloadUrl:new B.default.Variant("",[]),useStepResultIdForStepTransactions:new B.default.Flag,applyMobileRestrictionFromDate:new B.default.Configuration(17235072e5),removeMobileTrialRestrictions:new B.default.Flag,appiumConnectionRetryCount:new B.default.Configuration(0),appiumConnectionRequestTimeout:new B.default.Configuration(12e4),DFBrowserVersion:new B.default.Variant("latest",["latest","latest-1","latest-2"]),enableFixForCustomExtensionForLT:new B.default.Flag(!1)},B.default.register("default",this.flags)}setProjectId(e){B.default.setCustomStringProperty("projectId",e)}setProjectType(e){B.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){B.default.setCustomStringProperty("productType",e)}setCompanyId(e){B.default.setCustomStringProperty("companyId",e)}setPlanType(e){B.default.setCustomStringProperty("planType",e)}setIsPOC(e){B.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){B.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){B.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(B.default.setup(gd,e),Lw).catch(t=>_m.error("failed to get feature flag status",t))}},O=new Hc});var Mm={};H(Mm,{install:()=>Nw,isReady:()=>Fw,start:()=>Uw});var Om,Lm,Dm,zc,qc,Mw,Nw,Uw,Fw,Nm=w(()=>{"use strict";Om=I(require("fkill")),Lm=I(require("p-retry"));Yr();Ve();F();Ys();le();Dm="chromedriver",zc=9515,qc=`http://localhost:${zc}/wd/hub`,Mw=[`--port=${zc}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],Nw=async()=>{let s=O.flags.chromedriverCdnBinariesUrl.getValue(),e=ke(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await Mi(mt(),`${Dm} --detect_chromedriver_version ${e}`)},Uw=async()=>{process.env.NODE_OPTIONS="",await(0,Om.default)(`:${zc}`,{silent:!0}),await Jt(Dm).start(Mw,!0)},Fw=async({chromeBinaryLocation:s})=>{await(0,Lm.default)(async()=>{var n;let e=await be(`${qc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await We({url:`${qc}/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 Fs(`${qc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var Qs={};H(Qs,{getSessionPlayerFolder:()=>Xc,prepareChromeDriver:()=>Xs,prepareCustomExtension:()=>Jc,prepareExtension:()=>Yc,preparePlayer:()=>hr});async function Jc(s,e=!1){if(!s)return;if(ke(s)){let n=Xr.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Bw(s)>Kc&&!e)throw new x(Um);return await Ke(s,n),n}let t=Xr.resolve(s);if(!Bm.existsSync(t))throw new x(`Failed to find custom extension in location: ${t}`);if(Rc(t)>Kc&&!e)throw new x(Um);return t}async function Bw(s){let e=(Ve(),Fe(ze));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Ui.warn("failed to download custom extension",{err:t}),new x(`Failed to download custom extension from location: ${s}`)}}function Yc(s){Ui.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:bi(t)}));return Ft(()=>oe(e,({location:t,path:r})=>Ti(t,r)),"prepareExtension",$m,e)()}async function Xs(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(Nm(),Mm));try{await i.install(),await i.start(),t||await i.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof jr||(Ui.error(a,{...s,...Oi(),error:(0,jm.serializeError)(o)}),console.log(`
|
|
11
11
|
1. If you don't have Chrome, please install it from https://www.google.com/chrome.
|
|
12
12
|
2. If Chrome is installed, please verify it's binary directory:
|
|
13
13
|
- installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
|
|
14
14
|
- exists in your PATH environment variables.
|
|
15
15
|
3. Try adding --chrome-binary-location flag to Testim CLI specifying the exact location of chrome binary in your computer (e.g on Windows "C:/Program Files/Google/Chrome/Application/chrome.exe").
|
|
16
|
-
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),o}}async function Bw(){let s=`${Ds}/extension/sessionPlayer_LATEST_RELEASE`;return(await Nt(s)).body.toString("utf8")}async function jw(s,e){if(!_e(s)||_e(s)&&e||We)return s;let t=await Bw();return`${s}-${t}`}function Zc(){let s=ft();return Zr.resolve(s,"testim-bin")}function $w(){let s=Zc();return Zr.resolve(s,"sessionPlayer.zip")}async function Wm(s,e,t=!1){try{return await wi(s,e),await nt(e,Zc())}catch(r){if(t)throw r;return await Wm(s,e,!0)}}async function yr(s,e){Fi.info("prepare player",{location:s,canary:e});let t=$w();return Bt(async()=>{let r=await jw(s,e);return await Wm(r,t),{}},"preparePlayer",$m,[s,e,t])()}var Fm,Bm,Zr,jm,Fi,$m,Yc,Um,tn=v(()=>{"use strict";Fm=I(require("ms")),Bm=I(require("fs")),Zr=I(require("path"));de();Jt();jm=require("serialize-error");W();Wc();Y();F();Fi=x("prepare runner and testim start"),$m=(0,Fm.default)("0.5 day"),Yc=16,Um=`The size of the custom extension is more than ${Yc}MB`});function Ww(){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 ji(){let s=Ww(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new C(`Unsupported platform: ${s}`);let r=parseInt(sn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},i={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},o=`${e}/${t[s]}/${sn}/${n[s]}.zip`,a=Bi.join(el,n[s]),l=`${a}.zip`,c=Bi.join(a,i[s]);if(await he(c))return c;if(!await he(l)){let m=(0,tl.default)("Downloading Chromium").start();try{await Vm.promises.mkdir(el),await Je(o,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,tl.default)("Extracting Chromium").start();try{await nt(l,el)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Vm,rn,Bi,tl,sn,el,rl=v(()=>{"use strict";Vm=I(require("fs")),rn=I(require("os")),Bi=I(require("path")),tl=I(require("ora"));Y();F();sn="1000968",el=Bi.join(Ft,`chrome-${sn}`)});async function qm(s,e){return br=s,ol=e,await sl()}function zm(s,e){br=e.projectId,ol=e.token,nn=e.userAccessKey,it=s.token,an=al(it),cn=s.refreshToken,nl=s.ngrokToken,il=s.isNgrokWhitelisted,Gm=e.publicIp,Hm=e.initializedFromCache}function Gw(s=br,e=ol){return Bt(()=>(on.info("request to get cli token from server"),Ve({url:`${fe}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Vw*10,{projectId:s,token:e})()}async function Hw(){on.info("request to refresh JWT cli token from server");let s=await Ve({url:`${fe}/auth/refreshToken`,body:{token:it,refreshToken:cn}});return it=s.token,an=al(it),s.refreshToken&&(cn=s.refreshToken),it}async function sl(){try{let s=await Gw();return on.info("successfully get cli token from server"),it=s.token,an=al(it),cn=s.refreshToken,nl=s.ngrokToken,il=s.isNgrokWhitelisted,it}catch(s){throw s.message.includes("Unauthorized")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(on.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:br}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function al(s){return require("jsonwebtoken").decode(s).exp*1e3}async function At(){if(!an)return sl();let s=O.flags.accessTokenExpiryMargin.getValue();if(an<Date.now()+4*s)try{return await Hw()}catch(e){return on.error("failed to refresh token, executing fallback",e),sl()}return it}function $i(){return cn}function Tr(){return it?{uid:require("jsonwebtoken").decode(it).id,ngrokToken:nl,isNgrokWhitelisted:il}:{}}async function Wi(){if(!nn||!br)return;if(await cl({userAccessKey:nn,projectId:br}))return nn;let e=`user access key "${nn}" is invalid for project "${br}"`;throw new C(e)}function Vi(){return Gm}function Gi(){return Hm}var on,it,an,cn,nl,il,br,ol,nn,Gm,Hm,Vw,ot=v(()=>{"use strict";de();Ge();Jt();Y();W();ge();le();on=x("testim-custom-token"),br=null,ol=null,Vw=5*60*1e3});var Km={};H(Km,{isCi:()=>es});var es,Hi=v(()=>{"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:()=>Ol,clearTestResult:()=>Pl,deleteCloudflareTunnel:()=>Nl,fetchLambdatestConfig:()=>Al,fixGridAppIDStructure:()=>jl,forceUpdateCloudflareTunnelRoutes:()=>Ml,getAllGrids:()=>Rl,getAppDetails:()=>dn,getApplitoolsIntegrationData:()=>Ll,getBrowserStackSessionMetaData:()=>tv,getCloudflareTunnel:()=>Dl,getEditorUrl:()=>Qw,getGridSlot:()=>Sl,getHybridGridProvider:()=>El,getLabFeaturesByProjectId:()=>Cl,getMobileDevicesFromGrid:()=>Fl,getRealData:()=>xl,getS3Artifact:()=>un,getS3ArtifactText:()=>pl,getSuiteTestList:()=>yl,getTestPlan:()=>Xw,getTestPlanTestList:()=>hl,getTestResults:()=>vr,getUsageForCurrentBillingPeriod:()=>bl,initializeUserWithAuth:()=>Il,isTestResultCompleted:()=>Tl,keepAliveCompanySlots:()=>Gl,keepAliveGrid:()=>wl,loadSfdcCredential:()=>dl,loadTest:()=>pn,releaseCompanySlot:()=>Wl,releaseGridSlot:()=>vl,reportExecutionFinished:()=>qi,reportExecutionStarted:()=>gl,requestCompanySlot:()=>$l,saveRemoteStep:()=>kl,saveTestPlanResult:()=>ml,updateCompanySlot:()=>Vl,updateExecutionTests:()=>fl,updateRemoteRunFailure:()=>Ul,updateTestDataArtifact:()=>Ki,updateTestResult:()=>zi,updateTestStatus:()=>wr,uploadAppToGrid:()=>Bl,uploadRunDataArtifact:()=>_l,validateUserAccessKey:()=>cl});async function ts(){let s=await At();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Ie({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await ts(),o={...t,...i};return Ve({url:`${fe}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function Kw(s,e,t,r={},n=void 0){let i=await ts(),o={...r,...i};return await $s(`${fe}${s||""}`,e,t,o,n)}async function ln(s,e){let t=await ts();return await Ec(`${fe}${s||""}`,e,t)}async function Jw(s,e){let t=await ts();return await js(`${fe}${s||""}`,e,t)}async function Yw(s,e){let t=await ts();return await Ws(`${fe}${s||""}`,e||void 0,t)}async function Re(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,Z.default)(()=>Re(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function pl(s){return(0,Z.default)(()=>Yw(`/storage${s}`))}async function Xw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,Z.default)(()=>Re("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function dl({branch:s,projectId:e}){let t=await(0,Z.default)(()=>Re(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function pn({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,Z.default)(()=>Re(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function ml(s,e,t){return(0,Z.default)(()=>Ie({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function wr(s,e,t,r,n,i,o=te){return(0,Z.default)(()=>ln("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:qw,...i}),{retries:o,factor:1})}function fl(s,e,t,r,n,i,o,a){return(0,Z.default)(()=>ln("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:te,factor:1})}async function gl({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Hi(),Km));return Ie({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function qi(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,Z.default)(()=>ln("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function hl(s,e,t,r,n){return(0,Z.default)(()=>Ie({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function yl({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,Z.default)(()=>Ie({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:te,factor:1})}async function dn({appId:s,projectId:e}){try{return await(0,Z.default)(()=>Re(`/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 bl(s){try{return await(0,Z.default)(()=>Re(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){Ct.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Tl(s,e,t){return(0,Z.default)(()=>Re(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function vr(s,e,t,r){return(0,Z.default)(()=>Re(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function wl(s,e){return Ie({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function vl(s,e,t,r,n){return Ie({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function El(s){return Ie({url:"/grid/hybrid/provider",body:s})}function Sl(s){return(0,Z.default)(()=>Re("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Il({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d}){var m,u;try{return await(0,Z.default)(()=>Ve({url:`${fe}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d}}),{retries:te,factor:1})}catch(f){if(Ct.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((u=f.code)!=null&&u.includes("ENOTFOUND"))throw new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",y=h.clientMessage.bgColor||"bgBlack";console.log(ll.default[y](ll.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Ct.error("Error parsing error message from server",f)}throw f}}async function Qw(){if(Ls)return{editorUrl:Ls};try{return await(0,Z.default)(()=>Re("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return Ct.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Rl(s){return(0,Z.default)(()=>Re("/grid",{companyId:s}),{retries:te,factor:1})}function xl(s,e,t){return(0,Z.default)(()=>Re(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function zi(s,e,t,r,n){return(0,Z.default)(()=>Ie({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function Pl(s,e,t,r){return(0,Z.default)(()=>Ie({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function kl(s,e,t,r){return(0,Z.default)(()=>Ie({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function Zw(s){return s.startsWith("/")?s:`/${s}`}function ev(s,e,t){let r=Zw(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Ym(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,l=`${e}/${t}/${a}`,c=ev(l,Ad,s),d=Buffer.from(Jm.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,Z.default)(()=>Kw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),c}function Ol({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,Z.default)(()=>Ie({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function Ll(s){try{return await Re(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Ct.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Dl(s,e){try{return await ln("/tunnel",{companyId:s,routes:e})}catch(t){return Ct.warn("could'nt get tunnel.",{err:t}),{}}}async function Ml(s,e){try{return await Ie({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Ct.warn("could'nt get tunnel.",{err:t});return}}async function Nl(s,e){try{return await Jw(`/tunnel/${e}`,{companyId:s})}catch(t){Ct.warn("could'nt get tunnel.",{err:t});return}}function Ul(s){return Ve({url:`${fe}/result/remoteRunFailure`,body:s})}async function Fl({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${zw}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,Z.default)(()=>Re(i,{projectId:s}),{retries:te,factor:1})}catch(o){return Ct.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function Bl({projectId:s,gridId:e,app:t,timeout:r}){return(0,Z.default)(()=>Ie({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function jl(s){return(0,Z.default)(()=>Ie({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function $l(s,e){return(0,Z.default)(()=>Ie({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Wl(s,e,t){return(0,Z.default)(()=>Ie({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Vl(s,e,t){return(0,Z.default)(()=>ln("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Gl(s,e,t){return Ie({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function tv(s,e){return await be(`${Ms}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function cl(s){try{return await Re("/v2/project/validateUserAccessKey",s),!0}catch(e){return Ct.error("error validating user access key",{error:e}),!1}}var ll,Qt,Jm,Z,ul,qw,Ct,te,zw,Al,Cl,_l,Ki,ge=v(()=>{"use strict";ll=I(require("chalk")),Qt=I(require("lodash")),Jm=I(require("pako"));F();de();ne();Ge();ot();Z=I(require("p-retry")),ul=I(require("object-hash"));Y();W();qw=ze(),Ct=x("testim service api"),te=3,zw="/grid";Al=async()=>(0,Z.default)(()=>Re("/grid/lt/config"),{retries:te,factor:1}),Cl=async s=>(0,Z.default)(()=>Re(`/labFeature/v2/project/${s}`),{retries:te,factor:1});_l=Qt.memoize(async(s,e,t,r)=>{if(!Qt.isEmpty(r))return await Ym(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,ul.default)(r)}:${e}:${t}`),Ki=Qt.memoize(async(s,e,t,r,n)=>!r||Qt.isEmpty(r)?void 0:await Ym(s,e,t,JSON.stringify((()=>{let o=Qt.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{o[l]&&Object.assign(o,{[l]:_c.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,ul.default)(r)}:${e}:${t}`)});async function Xm(){let s=await Promise.any(rv.map(async e=>{try{return await be(e)}catch{return null}}));return s==null?void 0:s.ip}var rv,Qm=v(()=>{"use strict";Ge();rv=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});function Ji(){return ze()}var Hl=v(()=>{"use strict";F()});var Zt={};H(Zt,{getSessionPlayer:()=>X,options:()=>zl});var Yi,zl,ql,X,Te=v(()=>{"use strict";Yi=require("path");W();zl={playerPath:void 0},X=()=>{if(ql)return ql;let s=($e(),Me(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(tn(),Me(en)),t=e(),r=zl.playerPath?(0,Yi.resolve)(zl.playerPath,"src/background/sessionPlayerInit.ts"):(0,Yi.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),ql=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(pc),n}});function iv(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(Te(),Me(Zt)).getSessionPlayer()}catch{}})}function ov(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let n=r.color||"yellow",i=r.bgColor||"bgBlack";console.log(Kl.default[i](Kl.default[n](r.text)))})}async function mn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?nv:sv,f=Ji(),h=xc(),g=await Pm(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Xm()}catch(b){Zm.error("failed to get public ip",b)}let T=!0;U("before initializeUserWithAuth");let w=await Bt(async()=>(iv(a),T=!1,await Il({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:y,gridId:l,grid:c,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:y})();return ov(w),s.publicIps=[w.clientPublicIp],U("after initializeUserWithAuth"),y&&w.clientPublicIp&&w.clientPublicIp!==y&&(Zm.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:w.clientPublicIp}),s.publicIps.push(y)),zm(w.authData,{projectId:e,token:t,userAccessKey:r,publicIp:w.clientPublicIp,initializedFromCache:T}),w}var Kl,Zm,sv,nv,ef=v(()=>{"use strict";Kl=I(require("chalk"));$e();ge();Jt();ot();Qm();ne();W();le();Hl();F();Qr();Zm=x("initializeUserWithAuth"),sv=1e3*60*5,nv=1e3*60*60*10});async function sf(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await ji():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 yr(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await Qc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Xc(s.installCustomExtension,n)}return await e,t}async function nf(s){var o;av.info("prepare MockNetwork",{location:s});let e=await Ac(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>tf*1e6)throw new Error(`${Jl} exceeded ${tf}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Jl} cannot be parsed.${Xi.EOL}${a}`)}let n=new rf.default;if(!n.validate(jc,r)){let a=(o=n.errors)==null?void 0:o.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Xi.EOL);throw new Error(`${Jl} is malformed.${Xi.EOL}${a}`)}return r.entries}var Xi,rf,tf,Jl,av,Yl=v(()=>{"use strict";Xi=I(require("os"));F();am();tn();rf=I(require("ajv"));ne();rl();ef();tf=1,Jl="JSON file supplied to --mock-network-pattern",av=(W(),Me(gc)).getLogger("prepare runner")});function af(s,e=process){async function t(r){await ce(oe(of,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{fn.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(fn.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",()=>{fn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw fn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw fn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function rs(s){of.push(s)}var fn,of,gn=v(()=>{"use strict";W();F();fn=x("process-handler"),of=[]});function eu(s,e){var o;let t=s.canary?"-master.zip":".zip",r=`${e?vd:Ds}/extension/testim-headless${t}`,n=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(o=s.company)==null?void 0:o.companyId,projectId:s.project});return n||(mv.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),n="https://testimstatic.blob.core.windows.net/extension/testim-headless.zip"),!(s.ext||s.extensionPath)&&n&&(r=n,s.testimHeadlessExtensionDownloadUrl=n),{chrome:r,"edge-chromium":r}}function df(s){let{chrome:e}=eu(s,!1);return e}function Zi(s){let e=`${Ds}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var mv,hn=v(()=>{"use strict";de();le();W();mv=x("runOptionsUtils")});function yf(s){We||(s!=null&&s.userId||(s={anonymousId:hf}),gf.identify(s))}function ht(s,e){return yn("ci",s,e)}function yn(s,e,t){if(We)return;let r=s?{userId:s}:{anonymousId:hf};gf.track(Object.assign(r,{event:e,properties:t}))}var ff,gf,hf,ss=v(()=>{"use strict";de();ff=require("@segment/analytics-node"),gf=new ff.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),hf=require("crypto").randomBytes(20).toString("hex")});function bf(s){return s.start&&yn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Tf(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=Zi(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 wf=v(()=>{"use strict";hn();ss();Y()});var vf,gv,hv,tu,Ef=v(()=>{"use strict";vf="TST_CREDS",gv=["username","password"],hv="$encrypted",tu={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(vf)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[vf]:this.proxyPlaceholder})}}});async function If(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await yl({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 ru(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 su(s,e){let t=s.mode===q.EXTENSION?Er:Tn,r=Sf.difference(Hs(s,e),t);if(r.length>0)throw ht("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Sf,Er,Tn,eo=v(()=>{"use strict";Sf=I(require("lodash"));F();ss();ge();Y();ne();Er=["edge-chromium","chrome"],Tn=[...Er,"firefox","safari","safari technology preview"]});function ro(s){let{platform:e}=process;e==="win32"?(0,to.exec)(`start chrome ${s}`):e==="darwin"?(0,to.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,to.exec)(`google-chrome ${s}`)}var to,nu=v(()=>{"use strict";to=require("child_process")});var lu={};H(lu,{doLogin:()=>cu,getProjectId:()=>yv,getToken:()=>bv});async function yv(){return Cf("projectId")}async function bv(){return Cf("token")}function Af(s,e){return Promise.race([s,ae(e).then(()=>{throw new ie("timeout")})])}async function Tv(){let s=(await import("express")).default(),e=async function(){return Af(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),Ae)),{editorUrl:n}=await r();ro(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function cu({overwriteExisting:s=!0,projects:e=null}={}){let t=iu.homedir(),r=ou.join(t,".testim");if(await he(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Af(Tv(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,l.succeed(),await Rf(r,i);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=c.project.ci.token,i.projectId=c.project.id,await Rf(r,i);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Rf(s,e){await au.promises.writeFile(s,so.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function Cf(s){let e=iu.homedir(),t=ou.join(e,".testim"),r=await he(t),n={};if(r)try{n=so.parse((await au.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var iu,ou,so,au,no=v(()=>{"use strict";iu=I(require("os")),ou=I(require("path")),so=I(require("yaml"));F();au=require("fs");Y();nu()});var Mf={};H(Mf,{process:()=>Cv});var pu,_f,io,Of,jt,De,Lf,wv,Le,fu,vv,Ev,Pf,Df,Sv,du,mu,gu,uu,xt,Iv,p,Rv,Av,kf,Cv,Nf=v(()=>{"use strict";pu=I(require("ms")),_f=I(require("chalk")),io=I(require("fs")),Of=I(require("url")),jt=I(require("lodash")),De=I(require("path"));F();hn();wf();Jt();Lf=require("commander");ne();Y();Fr();F();le();Ef();eo();wv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Le=(s,e)=>(e.push(s),e),fu=new Lf.Command,vv=s=>s.split(","),Ev=(s,e)=>!s||s.length===0?e:s,Pf=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Df=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}fu.help(g=>g.split(`
|
|
16
|
+
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),o}}async function jw(){let s=`${Os}/extension/sessionPlayer_LATEST_RELEASE`;return(await Mt(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 Xc(){let s=mt();return Xr.resolve(s,"testim-bin")}function Ww(){let s=Xc();return Xr.resolve(s,"sessionPlayer.zip")}async function Wm(s,e,t=!1){try{return await Ti(s,e),await st(e,Xc())}catch(r){if(t)throw r;return await Wm(s,e,!0)}}async function hr(s,e){Ui.info("prepare player",{location:s,canary:e});let t=Ww();return Ft(async()=>{let r=await $w(s,e);return await Wm(r,t),{}},"preparePlayer",$m,[s,e,t])()}var Fm,Bm,Xr,jm,Ui,$m,Kc,Um,Zs=w(()=>{"use strict";Fm=I(require("ms")),Bm=I(require("fs")),Xr=I(require("path"));de();Kt();jm=require("serialize-error");W();jc();Y();F();Ui=C("prepare runner and testim start"),$m=(0,Fm.default)("0.5 day"),Kc=16,Um=`The size of the custom extension is more than ${Kc}MB`});function Vw(){let s=en.type().toLowerCase();return s==="darwin"?en.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?en.arch()==="x64"?"win64":"win32":"linux"}async function Bi(){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 x(`Unsupported platform: ${s}`);let r=parseInt(tn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},i={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},o=`${e}/${t[s]}/${tn}/${n[s]}.zip`,a=Fi.join(Qc,n[s]),l=`${a}.zip`,c=Fi.join(a,i[s]);if(await he(c))return c;if(!await he(l)){let m=(0,Zc.default)("Downloading Chromium").start();try{await Vm.promises.mkdir(Qc),await Ke(o,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,Zc.default)("Extracting Chromium").start();try{await st(l,Qc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Vm,en,Fi,Zc,tn,Qc,el=w(()=>{"use strict";Vm=I(require("fs")),en=I(require("os")),Fi=I(require("path")),Zc=I(require("ora"));Y();F();tn="1000968",Qc=Fi.join(Ut,`chrome-${tn}`)});async function qm(s,e){return yr=s,nl=e,await tl()}function zm(s,e){yr=e.projectId,nl=e.token,rn=e.userAccessKey,nt=s.token,nn=il(nt),on=s.refreshToken,rl=s.ngrokToken,sl=s.isNgrokWhitelisted,Gm=e.publicIp,Hm=e.initializedFromCache}function Hw(s=yr,e=nl){return Ft(()=>(sn.info("request to get cli token from server"),We({url:`${fe}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Gw*10,{projectId:s,token:e})()}async function qw(){sn.info("request to refresh JWT cli token from server");let s=await We({url:`${fe}/auth/refreshToken`,body:{token:nt,refreshToken:on}});return nt=s.token,nn=il(nt),s.refreshToken&&(on=s.refreshToken),nt}async function tl(){try{let s=await Hw();return sn.info("successfully get cli token from server"),nt=s.token,nn=il(nt),on=s.refreshToken,rl=s.ngrokToken,sl=s.isNgrokWhitelisted,nt}catch(s){throw s.message.includes("Unauthorized")?new x("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(sn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:yr}),new x(`While trying to retrieve CLI token, caught error: ${s}`))}}function il(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Rt(){if(!nn)return tl();let s=O.flags.accessTokenExpiryMargin.getValue();if(nn<Date.now()+4*s)try{return await qw()}catch(e){return sn.error("failed to refresh token, executing fallback",e),tl()}return nt}function ji(){return on}function br(){return nt?{uid:require("jsonwebtoken").decode(nt).id,ngrokToken:rl,isNgrokWhitelisted:sl}:{}}async function $i(){if(!rn||!yr)return;if(await ol({userAccessKey:rn,projectId:yr}))return rn;let e=`user access key "${rn}" is invalid for project "${yr}"`;throw new x(e)}function Wi(){return Gm}function Vi(){return Hm}var sn,nt,nn,on,rl,sl,yr,nl,rn,Gm,Hm,Gw,it=w(()=>{"use strict";de();Ve();Kt();Y();W();ge();le();sn=C("testim-custom-token"),yr=null,nl=null,Gw=5*60*1e3});var Km={};H(Km,{isCi:()=>Qr});var Qr,Gi=w(()=>{"use strict";Qr=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var Re={};H(Re,{addTestRetry:()=>kl,clearTestResult:()=>xl,deleteCloudflareTunnel:()=>Dl,fetchLambdatestConfig:()=>Il,fixGridAppIDStructure:()=>Fl,forceUpdateCloudflareTunnelRoutes:()=>Ll,getAllGrids:()=>Sl,getAppDetails:()=>un,getApplitoolsIntegrationData:()=>_l,getBrowserStackSessionMetaData:()=>rv,getCloudflareTunnel:()=>Ol,getEditorUrl:()=>Zw,getGridSlot:()=>vl,getHybridGridProvider:()=>wl,getLabFeaturesByProjectId:()=>Rl,getMobileDevicesFromGrid:()=>Nl,getRealData:()=>Al,getS3Artifact:()=>cn,getS3ArtifactText:()=>ll,getSuiteTestList:()=>gl,getTestPlan:()=>Qw,getTestPlanTestList:()=>fl,getTestResults:()=>wr,getUsageForCurrentBillingPeriod:()=>hl,initializeUserWithAuth:()=>El,isTestResultCompleted:()=>yl,keepAliveCompanySlots:()=>Wl,keepAliveGrid:()=>bl,loadSfdcCredential:()=>ul,loadTest:()=>ln,releaseCompanySlot:()=>jl,releaseGridSlot:()=>Tl,reportExecutionFinished:()=>Hi,reportExecutionStarted:()=>ml,requestCompanySlot:()=>Bl,saveRemoteStep:()=>Cl,saveTestPlanResult:()=>pl,updateCompanySlot:()=>$l,updateExecutionTests:()=>dl,updateRemoteRunFailure:()=>Ml,updateTestDataArtifact:()=>zi,updateTestResult:()=>qi,updateTestStatus:()=>Tr,uploadAppToGrid:()=>Ul,uploadRunDataArtifact:()=>Pl,validateUserAccessKey:()=>ol});async function Zr(){let s=await Rt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Se({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await Zr(),o={...t,...i};return We({url:`${fe}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function Jw(s,e,t,r={},n=void 0){let i=await Zr(),o={...r,...i};return await Bs(`${fe}${s||""}`,e,t,o,n)}async function an(s,e){let t=await Zr();return await wc(`${fe}${s||""}`,e,t)}async function Yw(s,e){let t=await Zr();return await Fs(`${fe}${s||""}`,e,t)}async function Xw(s,e){let t=await Zr();return await js(`${fe}${s||""}`,e||void 0,t)}async function Ie(s,e,t,r){let n=await Zr();return await be(`${fe}${s||""}`,e||void 0,n,r,t)}function cn(s,e){return(0,Z.default)(()=>Ie(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function ll(s){return(0,Z.default)(()=>Xw(`/storage${s}`))}async function Qw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,Z.default)(()=>Ie("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function ul({branch:s,projectId:e}){let t=await(0,Z.default)(()=>Ie(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function ln({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,Z.default)(()=>Ie(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function pl(s,e,t){return(0,Z.default)(()=>Se({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Tr(s,e,t,r,n,i,o=te){return(0,Z.default)(()=>an("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:zw,...i}),{retries:o,factor:1})}function dl(s,e,t,r,n,i,o,a){return(0,Z.default)(()=>an("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:te,factor:1})}async function ml({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Gi(),Km));return Se({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function Hi(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,Z.default)(()=>an("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function fl(s,e,t,r,n){return(0,Z.default)(()=>Se({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function gl({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,Z.default)(()=>Se({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:te,factor:1})}async function un({appId:s,projectId:e}){try{return await(0,Z.default)(()=>Ie(`/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 hl(s){try{return await(0,Z.default)(()=>Ie(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){At.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function yl(s,e,t){return(0,Z.default)(()=>Ie(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function wr(s,e,t,r){return(0,Z.default)(()=>Ie(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function bl(s,e){return Se({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function Tl(s,e,t,r,n){return Se({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function wl(s){return Se({url:"/grid/hybrid/provider",body:s})}function vl(s){return(0,Z.default)(()=>Ie("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function El({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d}){var m,u;try{return await(0,Z.default)(()=>We({url:`${fe}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d}}),{retries:te,factor:1})}catch(f){if(At.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new x("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((u=f.code)!=null&&u.includes("ENOTFOUND"))throw new x("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",y=h.clientMessage.bgColor||"bgBlack";console.log(al.default[y](al.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{At.error("Error parsing error message from server",f)}throw f}}async function Zw(){if(_s)return{editorUrl:_s};try{return await(0,Z.default)(()=>Ie("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return At.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Sl(s){return(0,Z.default)(()=>Ie("/grid",{companyId:s}),{retries:te,factor:1})}function Al(s,e,t){return(0,Z.default)(()=>Ie(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function qi(s,e,t,r,n){return(0,Z.default)(()=>Se({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function xl(s,e,t,r){return(0,Z.default)(()=>Se({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function Cl(s,e,t,r){return(0,Z.default)(()=>Se({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 Ym(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,l=`${e}/${t}/${a}`,c=tv(l,Id,s),d=Buffer.from(Jm.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,Z.default)(()=>Jw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),c}function kl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,Z.default)(()=>Se({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function _l(s){try{return await Ie(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return At.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Ol(s,e){try{return await an("/tunnel",{companyId:s,routes:e})}catch(t){return At.warn("could'nt get tunnel.",{err:t}),{}}}async function Ll(s,e){try{return await Se({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){At.warn("could'nt get tunnel.",{err:t});return}}async function Dl(s,e){try{return await Yw(`/tunnel/${e}`,{companyId:s})}catch(t){At.warn("could'nt get tunnel.",{err:t});return}}function Ml(s){return We({url:`${fe}/result/remoteRunFailure`,body:s})}async function Nl({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${Kw}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,Z.default)(()=>Ie(i,{projectId:s}),{retries:te,factor:1})}catch(o){return At.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function Ul({projectId:s,gridId:e,app:t,timeout:r}){return(0,Z.default)(()=>Se({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function Fl(s){return(0,Z.default)(()=>Se({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Bl(s,e){return(0,Z.default)(()=>Se({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function jl(s,e,t){return(0,Z.default)(()=>Se({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function $l(s,e,t){return(0,Z.default)(()=>an("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Wl(s,e,t){return Se({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function rv(s,e){return await be(`${Ls}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function ol(s){try{return await Ie("/v2/project/validateUserAccessKey",s),!0}catch(e){return At.error("error validating user access key",{error:e}),!1}}var al,Xt,Jm,Z,cl,zw,At,te,Kw,Il,Rl,Pl,zi,ge=w(()=>{"use strict";al=I(require("chalk")),Xt=I(require("lodash")),Jm=I(require("pako"));F();de();ne();Ve();it();Z=I(require("p-retry")),cl=I(require("object-hash"));Y();W();zw=qe(),At=C("testim service api"),te=3,Kw="/grid";Il=async()=>(0,Z.default)(()=>Ie("/grid/lt/config"),{retries:te,factor:1}),Rl=async s=>(0,Z.default)(()=>Ie(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Pl=Xt.memoize(async(s,e,t,r)=>{if(!Xt.isEmpty(r))return await Ym(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,cl.default)(r)}:${e}:${t}`),zi=Xt.memoize(async(s,e,t,r,n)=>!r||Xt.isEmpty(r)?void 0:await Ym(s,e,t,JSON.stringify((()=>{let o=Xt.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{o[l]&&Object.assign(o,{[l]:Pc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,cl.default)(r)}:${e}:${t}`)});async function Xm(){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,Qm=w(()=>{"use strict";Ve();sv=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});function Ki(){return qe()}var Vl=w(()=>{"use strict";F()});var Qt={};H(Qt,{getSessionPlayer:()=>X,options:()=>Hl});var Ji,Hl,Gl,X,Te=w(()=>{"use strict";Ji=require("path");W();Hl={playerPath:void 0},X=()=>{if(Gl)return Gl;let s=(je(),Fe(Be));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Zs(),Fe(Qs)),t=e(),r=Hl.playerPath?(0,Ji.resolve)(Hl.playerPath,"src/background/sessionPlayerInit.ts"):(0,Ji.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),Gl=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(lc),n}});function ov(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(Te(),Fe(Qt)).getSessionPlayer()}catch{}})}function av(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let n=r.color||"yellow",i=r.bgColor||"bgBlack";console.log(ql.default[i](ql.default[n](r.text)))})}async function pn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?iv:nv,f=Ki(),h=Ac(),g=await Pm(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Xm()}catch(b){Zm.error("failed to get public ip",b)}let T=!0;U("before initializeUserWithAuth");let v=await Ft(async()=>(ov(a),T=!1,await El({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:y,gridId:l,grid:c,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:y})();return av(v),s.publicIps=[v.clientPublicIp],U("after initializeUserWithAuth"),y&&v.clientPublicIp&&v.clientPublicIp!==y&&(Zm.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:v.clientPublicIp}),s.publicIps.push(y)),zm(v.authData,{projectId:e,token:t,userAccessKey:r,publicIp:v.clientPublicIp,initializedFromCache:T}),v}var ql,Zm,nv,iv,ef=w(()=>{"use strict";ql=I(require("chalk"));je();ge();Kt();it();Qm();ne();W();le();Vl();F();Yr();Zm=C("initializeUserWithAuth"),nv=1e3*60*5,iv=1e3*60*60*10});async function sf(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Bi():s.chromeBinaryLocation,e=Xs({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 hr(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await Yc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Jc(s.installCustomExtension,n)}return await e,t}async function nf(s){var o;cv.info("prepare MockNetwork",{location:s});let e=await Ic(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>tf*1e6)throw new Error(`${zl} exceeded ${tf}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${zl} cannot be parsed.${Yi.EOL}${a}`)}let n=new rf.default;if(!n.validate(Fc,r)){let a=(o=n.errors)==null?void 0:o.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Yi.EOL);throw new Error(`${zl} is malformed.${Yi.EOL}${a}`)}return r.entries}var Yi,rf,tf,zl,cv,Kl=w(()=>{"use strict";Yi=I(require("os"));F();am();Zs();rf=I(require("ajv"));ne();el();ef();tf=1,zl="JSON file supplied to --mock-network-pattern",cv=(W(),Fe(mc)).getLogger("prepare runner")});function af(s,e=process){async function t(r){await ce(oe(of,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{dn.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(dn.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",()=>{dn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw dn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw dn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function es(s){of.push(s)}var dn,of,mn=w(()=>{"use strict";W();F();dn=C("process-handler"),of=[]});function Ql(s,e){var o;let t=s.canary?"-master.zip":".zip",r=`${e?Td:Os}/extension/testim-headless${t}`,n=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(o=s.company)==null?void 0:o.companyId,projectId:s.project});return n||(fv.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),n="https://testimstatic.blob.core.windows.net/extension/testim-headless.zip"),!(s.ext||s.extensionPath)&&n&&(r=n,s.testimHeadlessExtensionDownloadUrl=n),{chrome:r,"edge-chromium":r}}function df(s){let{chrome:e}=Ql(s,!1);return e}function Qi(s){let e=`${Os}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var fv,fn=w(()=>{"use strict";de();le();W();fv=C("runOptionsUtils")});function yf(s){$e||(s!=null&&s.userId||(s={anonymousId:hf}),gf.identify(s))}function gt(s,e){return gn("ci",s,e)}function gn(s,e,t){if($e)return;let r=s?{userId:s}:{anonymousId:hf};gf.track(Object.assign(r,{event:e,properties:t}))}var ff,gf,hf,ts=w(()=>{"use strict";de();ff=require("@segment/analytics-node"),gf=new ff.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),hf=require("crypto").randomBytes(20).toString("hex")});function bf(s){return s.start&&gn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Tf(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new x("Agent port is not number");let t=Qi(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 wf=w(()=>{"use strict";fn();ts();Y()});var vf,hv,yv,Zl,Ef=w(()=>{"use strict";vf="TST_CREDS",hv=["username","password"],yv="$encrypted",Zl={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of hv)t[r]={[yv]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(vf)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[vf]:this.proxyPlaceholder})}}});async function If(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await gl({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function eu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function tu(s,e){let t=s.mode===q.EXTENSION?vr:yn,r=Sf.difference(Vs(s,e),t);if(r.length>0)throw gt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new x(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Sf,vr,yn,Zi=w(()=>{"use strict";Sf=I(require("lodash"));F();ts();ge();Y();ne();vr=["edge-chromium","chrome"],yn=[...vr,"firefox","safari","safari technology preview"]});function to(s){let{platform:e}=process;e==="win32"?(0,eo.exec)(`start chrome ${s}`):e==="darwin"?(0,eo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,eo.exec)(`google-chrome ${s}`)}var eo,ru=w(()=>{"use strict";eo=require("child_process")});var au={};H(au,{doLogin:()=>ou,getProjectId:()=>bv,getToken:()=>Tv});async function bv(){return xf("projectId")}async function Tv(){return xf("token")}function Af(s,e){return Promise.race([s,ae(e).then(()=>{throw new ie("timeout")})])}async function wv(){let s=(await import("express")).default(),e=async function(){return Af(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),Re)),{editorUrl:n}=await r();to(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function ou({overwriteExisting:s=!0,projects:e=null}={}){let t=su.homedir(),r=nu.join(t,".testim");if(await he(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Af(wv(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,l.succeed(),await Rf(r,i);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=c.project.ci.token,i.projectId=c.project.id,await Rf(r,i);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Rf(s,e){await iu.promises.writeFile(s,ro.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function xf(s){let e=su.homedir(),t=nu.join(e,".testim"),r=await he(t),n={};if(r)try{n=ro.parse((await iu.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var su,nu,ro,iu,so=w(()=>{"use strict";su=I(require("os")),nu=I(require("path")),ro=I(require("yaml"));F();iu=require("fs");Y();ru()});var Mf={};H(Mf,{process:()=>Cv});var lu,_f,no,Of,Bt,Le,Lf,vv,Oe,du,Ev,Sv,Pf,Df,Iv,uu,pu,mu,cu,xt,Rv,p,Av,xv,kf,Cv,Nf=w(()=>{"use strict";lu=I(require("ms")),_f=I(require("chalk")),no=I(require("node:fs")),Of=I(require("node:url")),Bt=I(require("lodash")),Le=I(require("node:path"));F();fn();wf();Kt();Lf=require("commander");ne();Y();Ur();F();le();Ef();Zi();vv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Oe=(s,e)=>(e.push(s),e),du=new Lf.Command,Ev=s=>s.split(","),Sv=(s,e)=>!s||s.length===0?e:s,Pf=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Df=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}du.help(g=>g.split(`
|
|
17
17
|
`).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!o(T)&&!i(T)&&!l(T)&&!c(T)&&!d(T)&&!m(T)&&!u(T)&&!f(T)&&!h(T)).join(`
|
|
18
|
-
`))},
|
|
18
|
+
`))},Iv=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(_f.default.yellow(`
|
|
19
19
|
WARNING: ${s} is deprecated. ${t}
|
|
20
|
-
`))},du=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:mu,argv:gu,exit:uu,cwd:xt}=global.process,Iv=["trace","debug","info","warn","error","silent"];Dc(gu,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));fu.description("Testim.io CLI").option("-h --help","output usage information",Df).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",Le,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Le,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Le,[]).option("--test-id [test-id]","test ID to run",Le,[]).option("-l, --label [label]","labels to search test by",Le,[]).option("-n, --name [test-name]","test name to run",Le,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",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",Le,[]).option("--test-plan-id [test-plan-id]","test plan to run",Le,[]).option("--suite [suite-name]","suite to run",Le,[]).option("--suite-id [suite-id]","suite ID to run",Le,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",Le,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(mu.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,pu.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,pu.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: ${du.join("/")}`,Le,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Le,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Le,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",Le,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",Le,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").parse(gu);p=fu.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))},kf=s=>{var r;if(!O.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=io.readFileSync(s);(r=tu)!=null&&r.containsEncryptedCredentials(t.toString())&&tu.injectProxyCredentialsStoreToGlobal()},Cv=async()=>{var y,T,w,b,E,S,A,D;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!gu.slice(2).length)throw Df(),new jr;if(p.version){let R="Testim CLI Version: ";mu.npm_package_version&&(console.log(R,mu.npm_package_version),uu(0));let N=ze();N&&(console.log(R,N),uu(0)),console.log("Could not find version, please check the package.json manually"),uu(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Tm(),p.clearFileCache&&Yr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=De.resolve(n);ym(R)}if(p.usePrefechedData&&wm(),p.playerRequirePath){let R=De.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let N=De.join(R,"tsconfig.node.json"),_=require("ts-node").register({project:N,ignore:[/node_modules/,new RegExp(`^${jt.escapeRegExp(De.relative(xt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:_.config.options.paths,baseUrl:_.config.options.baseUrl}),(Te(),Me(Zt)).options.playerPath=R;let V=require("module"),z=V.prototype.require;V.prototype.require=function(pe){return pe==="rox-alias"?z.call(this,"rox-node"):pe==="canvas"?{}:z.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=io.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new C("missing --proxy option");if(bf(p))return Tf(p);try{let R={};p.configFile?(kf(p.configFile),R=require(De.join(xt(),p.configFile)).config):p.optionsFile&&(R=require(De.join(xt(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(N=>{let k=wv(N);p[k]=Ev(p[k],R[N])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let i=((y=p.testConfig)==null?void 0:y.length)||((T=p.testConfigId)==null?void 0:T.length),o=((w=p.testPlan)==null?void 0:w.length)||((b=p.testPlanId)==null?void 0:b.length),a=((E=p.suite)==null?void 0:E.length)||((S=p.suiteId)==null?void 0:S.length);if(p.seleniumCapsFile)try{r=require(De.join(xt(),p.seleniumCapsFile))}catch(R){throw new C(`Failed to parse selenium caps file file error: ${R.message}`)}if((A=p.reporters)!=null&&A.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(De.join(xt(),p.chromeExtraPrefs))}catch(R){throw new C(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let N of R){let[k]=N.split("=");Pf.includes(k)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(N),k==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${k}), allowed values: ${JSON.stringify(Pf)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&kf(p.paramsFile),s={...s,...require(De.join(xt(),p.paramsFile))}}catch(R){throw new C(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new C(`Failed to parse params string error: ${R.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(Rv(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(De.join(xt(),p.sauceOptions)),N=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let _=R.browserName.toLowerCase();switch(_){case"microsoftedge":p.browser="edge";break;default:p.browser=_}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let k=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!N&&p.browser==="chrome"&&k)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new C(`Failed to parse saucelabs options file error: ${R.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(Av(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(De.join(xt(),p.browserstackOptions)),N=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"),!N&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new C(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(De.join(xt(),p.perfectoOptions)),N={location:"US East",securityToken:p.perfectoToken};p.perfecto={...N,...R}}catch(R){throw new C(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(De.join(xt(),p.testobjectOptions)),N={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...N,...R}}catch(R){throw new C(`Failed to parse test object options file error: ${R.message}`)}if(!p.project){let N=await(await Promise.resolve().then(()=>(no(),lu))).getProjectId();if(N)p.project=N;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}O.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=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 N=await(await Promise.resolve().then(()=>(no(),lu))).getToken();if(N)p.token=N;else throw new C("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let d=R=>R<=0||!Number.isInteger(R);if(d(p.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Er,...Tn].includes(p.browser))throw new C(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!Iv.includes(p.appiumLogLevel))throw new C(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new C("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||i||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new C("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!o&&(p.beforeParallel!==1||p.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new C("please define exactly one of --grid or --grid-id or --host");if((D=p.host)!=null&&D.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Of.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(N=>N.trim()).filter(Boolean);let R=p.resultLabel.filter(N=>N.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&mr()&&p.resultLabel.unshift(mr()),R.length)throw new C("A result label cannot exceed 250 characters")}let u=Zi(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new C("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new C("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new C("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||o))throw new C("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!jt.inRange(jt.parseInt(p.setRetention),1,11))throw new C("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let f="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new C(`--mock-network-har ${f}`);if(p.mockNetworkPattern)throw new C(`--mock-network-pattern ${f}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&jt.difference(p.codeCoverageReporter,du).length){let R=jt.difference(p.codeCoverageReporter,du);throw new C(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let 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"},g=Object.keys(h).filter(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&g.length){let R=g.length>1?"are":"is";throw new C(`${g.map(N=>h[N]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=io.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new C(`failed to parse field file error: ${R.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new C("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(Sv("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new C("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new C("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let R={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},N=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...N}}catch(R){throw new C(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
|
|
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 C("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?mr():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,extensionPath:p.extensionPath,extensionLocation:[p.extensionPath].filter(Boolean),playerLocation:p.playerPath||u,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 jf={};H(jf,{installAllLazyDependencies:()=>kv,lazyRequire:()=>at});async function at(s,e={}){let t=Hc(s);if(t)return t;let r;e.silent||(r=(0,Uf.default)(`Installing ${s} before first usage...`).start());try{let n=await Pv(s);return r&&r.succeed(),n}catch(n){xv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Bf(s),o=`${s}@${i}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${o}`;throw r&&r.fail(c),n}}async function Pv(s){return ns.has(s)||(ns.set(s,Ff(s)),ns.get(s).catch(()=>{ns.delete(s)})),ns.get(s)}async function Ff(s){let e=Hc(s);if(e)return e;let t=Bf(s),r=`${s}@${t}`;return await Ni(ft(),r),Yt(s)}async function kv(){let s=Object.keys(ec);for(let e of s)await Ff(e)}function Bf(s){let e=Object.entries(ec).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Uf,xv,ns,wn=v(()=>{"use strict";Uf=I(require("ora"));Qr();W();F();li();Qs();xv=x("lazy-require"),ns=new Map});var Wf={};H(Wf,{preloadTests:()=>vn});async function vn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await Bt(async()=>{let t=await oe(s.testId,r=>pn({...e,testId:r}),{concurrency:2});return $f.keyBy(t,"testData.id")},"loadTests",_v,[e,s.testId])()}var $f,_v,oo=v(()=>{"use strict";$f=I(require("lodash"));Jt();ge();F();_v=1e3*60*60*10});var hu,Ov,is,Vf,Gf,yu,Hf,qf=v(()=>{"use strict";F();Y();W();wn();hu=x("testimNgrok"),Ov=".whitelisted-ngrok.testim.io",is="",Gf=async(s,e={})=>{if(!e.ngrokToken)throw new C("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${re()}-${s.projectData.projectId}${Ov}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let i=await(await at("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(hu.info("replace https to http"),is=i.replace("https://","http://")):is=i,s.tunnelDiagnostics&&yu(),s.baseUrl=is},yu=async(s=!0)=>{try{let t=(await at("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===is);console.log("ngrok stats",n),hu.info("ngrok stats",{tunnel:n})}catch(e){hu.error("error collecting ngrok stats",{err:e})}s&&(Vf=setTimeout(()=>yu(),1e4))},Hf=async s=>{if(!is)return;clearTimeout(Vf),s.tunnelDiagnostics&&await yu(!1),await(await at("ngrok")).disconnect(is)}});var er,Tu,zf,Dv,Mv,bu,ao,lo,co,Nv,Kf,Jf,Yf=v(()=>{"use strict";er=I(require("os")),Tu=I(require("fs")),zf=I(require("child_process"));F();ge();Dv="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",Mv={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"}},bu=er.tmpdir(),ao=`${bu}/cloudflared`,lo=null,co=null,Nv=async()=>{if(await he(ao))return;let e=Mv[er.platform()+er.arch()];if(!e)throw new Error(`tunnel on ${er.platform()+er.arch()} platform is not supported.`);let t=e.extract?bu+e.path:ao;await Je(`${Dv}/${e.path}`,t),e.extract&&await nt(t,bu),await Tu.promises.chmod(ao,"755")},Kf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Dl(s.company.companyId,t),Nv()]);lo=r._id,co=zf.spawn(ao,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Ml(s.company.companyId,lo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Tu.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 lo&&e.push(Nl(s.company.companyId,lo)),co&&e.push(new Promise((t,r)=>{co.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),co.kill()})),await Promise.all(e)}});function Xf(s,e){if(e){if(!Vv.includes(e)){En.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var Qf,Zf,$t,eg,tg,rg,uo,sg,En,Fv,Bv,Sn,jv,$v,Wv,se,Vv,po=v(()=>{"use strict";Qf=I(require("ms")),Zf=I(require("p-retry")),$t=I(require("os")),eg=I(require("portfinder")),tg=I(require("child_process"));F();Ge();ge();rg=I(require("fs")),uo=I(require("fs/promises")),sg=require("path");Y();W();hn();ne();le();F();En=x("lambdatestService"),Fv="https://downloads.lambdatest.com/tunnel/v3",Bv={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"},Sn=`${$t.tmpdir()}/LT`,jv=`${Sn}/LT`,$v=(0,Qf.default)("15m"),Wv="2560x1440",se=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===L.TESTIM_LAMBDATEST||e.type===L.LAMBDATEST||e.type===L.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){se.isLambdatestGrid(e)&&(se.lambdatestConfigPromise||=Al(),se.lambdatestConfig=await se.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?$v:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await he(jv))return;let t=Bv[$t.platform()+$t.arch()];if(!t)throw new Error(`tunnel on ${$t.platform()+$t.arch()} platform is not supported.`);let r=`${Sn}.zip`;await Je(`${Fv}/${t}`,r),await nt(r,Sn)}static async chmodLtTunnel(e){if(!($t.platform()==="win32"||!await he(e))){try{await uo.access(e,rg.constants.X_OK);return}catch{}try{await uo.chmod(e,"777")}catch(r){throw En.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ae(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){se.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await eg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;se.tunnelName=re();let c=["--tunnelName",se.tunnelName,"--infoAPIPort",String(t)];if(O.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(O.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Mc(u)])}if(O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new C("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await se.delay(3e3),await se.chmodLtTunnel((0,sg.join)(Sn,"LT")),se.tunnel=tg.spawn("./LT",c,{cwd:Sn});let d="",m="";se.tunnel.stdout.on("data",u=>{d+=u.toString()}),se.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}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});En.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),En.error("Failed to start LT tunnel",{err:u}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!se.tunnel))return new Promise((t,r)=>{se.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),se.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,l){var T,w;if(!this.isActive)return{};let c=se.lambdatestConfig.CAPABILITIES[t]||{},d={...se.tunnelName&&{tunnel:!0,tunnelName:se.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:Xf(n,a==null?void 0:a.os)||Xf(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||se.lambdatestConfig.PLATFORM,resolution:se.lambdatestConfig.RESOLUTION??Wv,version:t==="safari"&&((w=o==null?void 0:o.lt)==null?void 0:w.safari_version)||c.version};if(l!==q.APPIUM&&l!==q.SELENIUM&&!f){let b=eu({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&_e(h)&&(m=[...m,h]),m.length||En.warn("No extension was loaded in LambdaTestService",{extUrls:b,extensionPath:h})}return O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&_e(g)&&(m=[...m,g]),{build:r,name:`${n} - ${i}`,selenium_version:se.lambdatestConfig.SELENIUM_VERSION,timezone:se.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},Vv=["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"]});var wu={};H(wu,{connect:()=>fo,disconnect:()=>go,serveTunneling:()=>Hv});var mo,ng,ig,Gv,fo,go,Hv,vu=v(()=>{"use strict";qf();gn();Yf();ot();mo=I(require("ora"));W();ne();po();ng=x("tunnel"),ig=s=>{var e;return[L.TESTIM_LAMBDATEST,L.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Gv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===L.HYBRID&&s.gridData.tunnel==="cloudflare"},fo=async s=>{if(!s.tunnel)return;let e=Tr(),t;try{ig(s)?(t=(0,mo.default)("Starting testim lambdatest tunnel...").start(),await se.connectTunnel(s)):Gv(s)?(t=(0,mo.default)("Starting testim cloudflare tunnel...").start(),await Kf(s)):(t=(0,mo.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 r.isInvalidCredsForLT&&(n="Could not connect to LambdaTest. Check your credentials and then try again."),ng.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
|
|
22
|
-
${r.stdoutResult}`:n)}},go=async s=>{if(s.tunnel)try{ig(s)?await se.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)}},Hv=async(s,e=new Promise(()=>{}))=>(await fo(s),rs(()=>go(s)),await e)});function qv(s){if(s.protocol)return s.protocol;if([L.TESTIM,L.BROWSERSTACK,L.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([L.TESTIM_ENTERPRISE,L.TESTIM_LAMBDATEST,L.DEVICE_FARM].includes(s.type)){let e=og.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function zv(s){let e=og.exec(s);return e==null?void 0:e[3]}function yo(s){var E,S,A,D,R,N,k,_,$,V,z;let e=s&&zv(s.host),t=s.port,r=s.path,n=s&&qv(s),i=s.token,o=s.slotId,a=(E=s.hybrid)==null?void 0:E.tunnel,l=(S=s.external)==null?void 0:S.user,c=(A=s.external)==null?void 0:A.key,d=s.type,m=d===L.HYBRID?a&&((N=(R=(D=s.hybrid)==null?void 0:D.external)==null?void 0:R[s.hybrid.tunnel])==null?void 0:N.user):l,u=d===L.HYBRID?a&&(($=(_=(k=s.hybrid)==null?void 0:k.external)==null?void 0:_[s.hybrid.tunnel])==null?void 0:$.key):c,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(V=s.mobileTokens)==null?void 0:V.androidToken,T=(z=s.mobileTokens)==null?void 0:z.iosToken,w=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:w,isSupportGrid:b}}async function Jv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(l){throw Qe.error("failed to get grid",{projectId:s,companyId:e,err:l}),new Error(gt.UNKNOWN)}if(Qe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Qe.error("invalid response - get grid",{res:o}),new Error(gt.UNKNOWN);if(o.status==="success"){if(o.grid.mode==="local")return{mode:"local"};((a=o.grid)==null?void 0:a.mode)==="custom"&&Object.assign(o.grid,ug(n));let l=yo(o.grid);return Kv(t,e,l.gridId,l.slotId,r,l.isSupportGrid),l}throw o.code==="not-found"?new tt(gt.NOT_FOUND):o.code==="no-available-slot"?new qt(`Failed to run test on ${r} - concurrency limit reached`):(Qe.error("invalid code error response - get grid",{res:o}),new tt(gt.UNKNOWN))}function cg(s){return Rl(s)}async function lg(s,e,t){let n=(t||await cg(s)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return yo(n)}async function Yv(s,e,t){let n=(t||await cg(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return yo(n)}async function Eu(s,e){let t=In[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete In[s],!a){if(!r){Qe.warn("failed to find grid slot id",{projectId:e});return}Qe.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await vl(o,e,r,n,i)}catch(l){Qe.error("failed to release slot",{projectId:e,err:l})}}}async function Xv(s){let e=Object.values(In).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid){Qe.info("keep alive worker slots",{projectId:s,slots:e});try{await wl(s,e)}catch(t){Qe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function Qv(s){ag=global.setInterval(Xv,1e4,s)}async function Zv(s){let e=Object.keys(In);if(e.length){Qe.warn("not all slots released before end runner flow",{projectId:s});try{await oe(e,t=>Eu(Number(t),s))}catch(t){Qe.error("failed to release all slots",{err:t,projectId:s})}}}async function eE(s){await Zv(s),clearInterval(ag)}function tE(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function rE(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function ug(s){let t=(()=>ho.isEmpty(s.testobjectSauce)?ho.isEmpty(s.saucelabs)?ho.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=tE(t,s),l=rE(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:l,key:a,gridId:re()}}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:i,useChromeLauncher:o,gridId:a,grid:l}=s;if(n||o||i)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 Yv(c,l,e);if(qs(s)||s.tunnelOnlyMode){Qe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new tt("Missing host or grid configuration")}async function mg(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:l,localTmaUrl:c,useLocalChromeDriver:d,useChromeLauncher:m,company:u}=t,f=Boolean(d||m||c),h=u==null?void 0:u.companyId;return Jv(o,h,r,s,t,()=>Sl({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:l,gridName:a,host:i,testResultId:n}))}var ho,Qe,In,og,ag,Kv,Rn,fg,os=v(()=>{"use strict";ho=I(require("lodash"));ge();W();F();ne();Y();Qe=x("grid-service"),In={},og=/(^(https?):\/{2})?(.*)/,ag=null;Kv=(s,e,t,r,n,i)=>{In[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};Rn={start:Qv,end:eE};fg=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:i}={}}=s,{gridId:o,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!o||!a||((a===L.TESTIM_LAMBDATEST||a===L.LAMBDATEST)&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==L.HYBRID||!i||!l||!d||!m))return e;let u=await El({companyId:i,gridId:o,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Qe.info("handling hybrid grid",{response:u,companyId:i});let f=yo({...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 Su(s,e,t){let r=as[s];if(!r)return;let{slotId:n}=r;if(delete as[s],!n){ct.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ct.info("release slot id",{companyId:e,slotId:n});try{await Wl(e,t,n)}catch(i){ct.error("failed to release slot",{companyId:e,err:i})}}async function sE(s,e){let t=Object.values(as).filter(Boolean);if(t.length!==0){ct.info("keep alive worker slots",{companyId:s,slots:t});try{await Gl(s,e,t)}catch(r){ct.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function nE(s,e){gg=global.setInterval(()=>sE(s,e),1e4)}async function iE(s,e){let t=Object.keys(as);if(t.length){ct.warn("not all slots released before end runner flow",{companyId:s});try{await oe(t,r=>Su(Number(r),s,e))}catch(r){ct.error("failed to release all slots",{err:r,companyId:s})}}}async function oE(s,e){await iE(s,e),clearInterval(gg)}async function yg(s,e,t){let r;try{r=await $l(s,e)}catch(n){throw ct.error("failed to get slot",{companyId:s,err:n}),new Error(gt.UNKNOWN)}if(ct.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ct.error("invalid response - get slot",{res:r}),new Error(gt.UNKNOWN);if(r.status==="success")return hg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new tt(gt.NOT_FOUND):r.code==="no-available-slot"?new qt("Failed to run test - concurrency limit reached"):(ct.error("invalid code error response - get slot",{res:r}),new tt(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 Vl(s,e,n),ct.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ct,as,gg,hg,Cn,cs=v(()=>{"use strict";ge();W();F();ne();Y();ct=x("slot-service"),as={},gg=null,hg=(s,e)=>{as[s]=e};Cn={start:nE,end:oE}});function Pn(){return bo||"master"}function Tg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){bo="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){bo=s.branch||s;return}bo=e?"master":void 0}var bo,Iu=v(()=>{"use strict";Y()});var kn,Ru,aE,Au,cE,To,wo,vo,Eo,So,Io=v(()=>{"use strict";F();ne();kn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===me.FAILED},Ru=s=>{let{status:e}=s;return e===me.ABORTED},aE=s=>{let{status:e}=s;return e===me.PASSED},Au=s=>s.runnerStatus===Pc.SKIPPED,cE=s=>s.testStatus===Ye.EVALUATING,To=(s,e)=>Object.values(s).filter(t=>{var r,n;return Au(t)&&(Xe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,wo=s=>Object.values(s).filter(e=>kn(e)&&cE(e)).length,vo=s=>Object.values(s).filter(kn),Eo=s=>Object.values(s).filter(aE),So=s=>Object.values(s).filter(Ru)});function uE(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Cu,Ro,lE,Ao,vg=v(()=>{"use strict";Cu=I(require("lodash"));W();Io();Ro=x("debug-reporter"),lE=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],Ao=class{constructor(e){this.options=e}onTestStarted(e,t){Ro.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;Ro.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:l,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Cu.default.omit(this.options,lE),company:Cu.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let l=uE(process.argv);Ro.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,i){let o=Eo(e).length,a=Object.keys(e).length-o;Ro.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var xu,Pt,_n=v(()=>{"use strict";ne();xu=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===L.DEVICE_FARM}},Pt=new xu});var ku={};H(ku,{Reporter:()=>pE});var tr,On,Sr,Co,Eg,Pu,pE,_u=v(()=>{"use strict";tr=I(require("chalk")),On=I(require("lodash"));F();ne();_n();Io();Sr={success:tr.default.green,warn:tr.default.yellow,error:tr.default.red},{CLI_MODE:Co}=Ut,Eg="device",Pu=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: ${tr.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?me.PASSED:me.FAILED,n=`(${e.testId})`,i=Sr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Si(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(Sr.error("Failed runs are:")),console.log(Sr.error(t.join(`
|
|
23
|
-
\r`)))}onTestPlanFinished(e,t,r,n,i){let o=vo(e),a=Eo(e),l=So(e),c=a.length,d=l.length,m=o.length,u="",f="";if(Pt.isTestStatusEnabled){let w=wo(e);u=` FAILED-EVALUATING: ${w}`,m-=w,f=` SKIPPED: ${To(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=Sr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Si(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=On.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=On.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=On.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=On.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let l=u=>{u.forEach((f,h)=>{var 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(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Co.APPIUM?Eg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${tr.default.underline(n)} slot from ${tr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Co.APPIUM?Eg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${tr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===Co.APPIUM?"device":"browser";if(n)console.log(Sr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(Sr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===Co.APPIUM?"Appium":"Selenium";console.log(Sr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},pE=Pu});var Du={};H(Du,{Reporter:()=>yE});function dE(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function mE(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 fE(s){return`${s.visitedUrlsJson||""}`}async function gE(s,e,t,r,n,i){function o(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:dE(u),classname:n,time:Nc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(kn(u)||Ru(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=kn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Au(u)&&Xe(u,i)&&Pt.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=mE(u),h["visited-urls-json"]=fE(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},w={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(Pt.isTestStatusEnabled){w.skipped=To(y,i);let b=wo(y);w.failures-=b,w["failure-evaluating"]=b}return{$:w,testcase:Object.keys(y).map(b=>o(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return vo(u).length+So(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Lu.Builder().buildObject(m)}catch(u){return hE(u)}}function hE(s){let e=new Lu.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 Lu,Sg,Ou,yE,Mu=v(()=>{"use strict";Lu=I(require("xml2js"));F();Sg=require("fs");_n();Io();Ou=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await gE(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Sg.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};yE=Ou});var Ig={};H(Ig,{Reporter:()=>bE});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 Nu,Uu,bE,Rg=v(()=>{"use strict";W();Nu=x("team-city-reporter");Uu=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){Nu.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,i,o){if(i){Nu.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='${o}']`)}onTestFinished(e,t,r){if(r){Nu.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)}']`)}},bE=Uu});var Ag={};H(Ag,{Reporter:()=>TE});var Fu,TE,Cg=v(()=>{"use strict";Fu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},TE=Fu});var xg={};H(xg,{Reporter:()=>wE});var Bu,wE,Pg=v(()=>{"use strict";F();nu();Bu=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 ro(t)}},wE=Bu});var ju,Q,kt=v(()=>{"use strict";vg();ju=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new Ao(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(_u(),ku));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Mu(),Du));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Rg(),Ig)),r.includes("console")&&Promise.resolve().then(()=>(_u(),ku)),r.includes("junit")&&Promise.resolve().then(()=>(Mu(),Du)),r.includes("json")&&Promise.resolve().then(()=>(Cg(),Ag)),r.includes("chrome")&&Promise.resolve().then(()=>(Pg(),xg))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,i){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var i;let n=t==null?void 0:t(...r);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||r))}}},Q=new ju});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:i,companyName:o,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:i,companyName:o,projectName:a,companyPlan:l,source:kg(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);ht("test-run-ci",y)}function Lg({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let w=_g({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,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){ht("test-run-ci-success",w);return}ht("test-run-ci-fail",{...w,failureReason:n.failureReason})}catch(w){f.error("failed to update test end analytics",{err:w})}}function Dg(s){ht("batch-run-ci",s)}var kg,$u=v(()=>{"use strict";ss();Hi();kg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:es&&e?"ci-with-user":es?"ci":e?"cli-with-user":s});var Ng,xo,Ug=v(()=>{"use strict";Ng=require("istanbul-lib-report"),xo=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,Ln,yt,$g,Po,Wu,Wg,vE,Vg,Gg,EE,SE,Hg,IE,RE,AE,CE,xE,qg,zg=v(()=>{"use strict";Fg=I(require("ora")),Bg=I(require("dayjs")),jg=I(require("test-exclude")),Ln=I(require("fs")),yt=I(require("path")),$g=I(require("istanbul-reports")),Po=I(require("istanbul-lib-report"));ge();Y();F();W();wn();Ug();Wu=x("test-run-status"),Wg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},vE=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)},EE=s=>s.substring(0,s.indexOf("?")),SE=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await at("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Hg=(s,e)=>`${yt.resolve(s,Vg(e))}.js`,IE=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await oe(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await oe(i.sources,async(o,a)=>{if(Gg(r,o))return;let l=Hg(e,o);await Ln.promises.mkdir(yt.parse(l).dir,{recursive:!0}),await Ln.promises.writeFile(l,i.sourcesContent[a])})})},RE={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(vE(e)&&(e=EE(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=yt.dirname(this.getPath(s));return yt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},AE=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=Po.createContext({dir:t,coverageMap:e,watermarks:Po.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Hg(r,a);return Ln.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new xo({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:RE}),$g.create(a,l).execute(o)}),i},CE=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await at("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Gg(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},xE=async(s,e)=>{let{mergeProcessCovs:r}=await at("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await xl(s,"testResult",`runId=${e}`)).data.docs;return await oe(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await un(l,9e4);await oe(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await pl(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},qg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Wu.info("start js coverage process");let n=(0,Fg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=yt.resolve(s.codeCoverageReportPath||"./coverage"),o=yt.resolve(i,`.js/${(0,Bg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?yt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([at("istanbul-lib-coverage"),xE(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Wu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await oe(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),w=await SE({sourceMapType:T,source:y,sourceMapDir:a});u[h]=w;let b=await CE(s,{source:y,sourceMap:w,functions:g});m.merge(b)}),await IE(s,o,u);let f=await AE(s,m,i,o);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof C?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Wu.error(c,{err:l})}}});var Kg={};H(Kg,{SELENIUM_PERF_MARKS:()=>Ce,SeleniumPerfStats:()=>Ir});var Ce,PE,Ir,us=v(()=>{"use strict";F();Ce={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},PE=["ALL",...Object.values(Ce)],Ir=class{constructor(){this.marks=Object.fromEntries(PE.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=re();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,Ai(r,50)],[`${t}_P95`,Ai(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Qg={};H(Qg,{initServer:()=>OE,mapFilesToLocalDrive:()=>Gu});function Gu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,ko[t.id]?{screenshot:ko[t.id]}:{})),Object.keys(_o).forEach(t=>{s.assets||={},s.assets[Xg[t]]=_o[t]}),s.assets||={},s.assets.screenshots=Object.values(ko)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function OE({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await at("multer"),n=typeof t=="string"?t:kE;await Vu.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=Dn.join(n,m.testResultId);try{await Vu.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=Dn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,Yg.default)();o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(ko[d.stepId]=l.file.path),d.testResultId&&_E.includes(d.subType)&&(_o[d.subType]||=[],_o[d.subType].push(l.file.path)),c.sendStatus(200)}),o.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new C(`Port ${s} is already in use`));default:return c(u)}}})}var Vu,Jg,Dn,Yg,kE,ko,_o,Xg,_E,Hu=v(()=>{"use strict";Vu=I(require("fs")),Jg=I(require("os")),Dn=I(require("path")),Yg=I(require("express"));Y();wn();kE=Dn.join(Jg.tmpdir(),"testim/rca/"),ko={},_o={},Xg={"test-log":"consoleLogs","har-file":"networkLogs"},_E=Object.keys(Xg)});var rr,qu,Oo,Zg=v(()=>{"use strict";rr=I(require("lodash"));F();W();qu=x("override-test-data-builder"),Oo=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return rr.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)&&!rr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):qu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(rr.isObject(e.overrideAllTestsData)&&!rr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):qu.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}qu.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 rr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=re();return{...e,resultId:i,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Lo(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ze.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Rr,Ze,LE,DE,ME,NE,Do,eh=v(()=>{"use strict";Rr=I(require("lodash"));F();ne();os();cs();ge();Y();W();kt();gn();zg();us();Hu();de();le();Zg();_n();Ze=x("test-run-status"),LE=mr(),DE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,ME=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,NE=ze();Do=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 i=Hs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:di||t.parallel||1,browser:i,gitBranch:LE,gitCommit:DE,gitRepoUrl:ME,runnerVersion:NE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w}=a,b={originalTestResultId:t,previousTestResultId:r,config:Rr.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w},Ol({projectId:n,runId:i,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,Q.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:i,projectData:o}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Ki(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){Ze.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:i,testRetryKey:r})}async testStartReport(e,t,r){if(Xe(e,this.options))return;let n=this.exportsGlobal;try{let i=await Lo(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...i},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(i){throw Ze.error("Failed to start test",{err:i}),i}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Ze.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Ye.EVALUATING&&Pt.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ye.EVALUATING} status`);return}if(c){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?me.PASSED:me.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Ye.QUARANTINE}`)}monitorMemoryUsage(e){let t=Uc();t.isOverThreshold&&Ze.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&Gu(o,Ze),o.resultUrl=qe(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Q.onTestFinished(o,e,i);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await Lo(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){Ze.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await 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 Ze.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=Oc;return e&&(n=i),Gr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g;let l=e.browser?Ks(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Hr(O,n)&&zs(a.nativeApp)&&!e.appId,d=Kt(e)&&(Gr(a.nativeApp,n)||c),m=Xe(a,e)||d,u={testId:a.testId,status:m?me.SKIPPED:me.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(i)}async endKeepAlive(e,t,r){e==="redis"&&await Cn.end(r,t),e==="mongo"&&await Rn.end(t)}async executionStart(e,t,r,n,i){Ze.info("execution started",{executionId:e});let{options:o}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=o;rs(()=>Promise.all([this.endKeepAlive(d,t,c),qi("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...O.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await Lo(o.beforeSuite,m),f=new Oo(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 w=async()=>{let b=Rr.cloneDeep(this.testRunStatus);await oe(Object.keys(b),async A=>{var _;let D=b[A],R=(_=D.config)==null?void 0:_.testData,N=D.testId,k=await Ki(t,N,A,R,l.defaults);k&&(delete D.config.testData,D.config.testDataUrl=k)});let E=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),S=gl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:E,intersections:o.intersections});return this.executionStartedPromise=S,S.catch(A=>Ze.error(A)),S};try{await w()}catch(b){Ze.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=Bc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===me.PASSED&&n++,m===me.SKIPPED&&i++,m===me.FAILED&&u===Ye.EVALUATING&&o++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Lo(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ze.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 qi("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Ze.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await fl(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function FE(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()&&_e(s))&&s){let r=ch(s);ds.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Ju(r)} current extension count: ${e.length}`),e.push(r)}}function uh(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;ds.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=Mo.basename(i));let l=Mo.join(process.cwd(),a),c=ch(l);ds.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${Ju(c)} current extension count: ${e.length}`),e.push(c)}function BE(s,e,t,r,n,i,o,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...ah];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":zu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":zu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1,"profile.password_manager_leak_detection":!1},w3c:!0};Ku(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Ku(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"]=zu.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+kc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),lh(r,c,o),a===q.EXTENSION&&uh(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return se.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function $E(s,e,t){let r={"pdfjs.disabled":!0};return O.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 ps(s){return`${s.width}x${s.height}`}function zE(s){let{platform:e}=s;if(!e)return ps(sh);let t=e.split(" ")[1];return e.startsWith("Windows")&&qE.has(t)?ps(VE):e==="Linux"?ps(WE):e.startsWith("macOS")?ps(GE):ps(e==="OS X El Capitan"||e==="OS X Yosemite"?HE:sh)}function KE(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(n["sauce:options"].screenResolution=zE(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let i=(0,oh.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,lt.merge(i,n,r)}return lt.merge(n,r)}return{}}function JE(s,e,t){return lt.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 YE(s){return s.perfecto?s.perfecto:{}}function XE(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 QE(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,i=r||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=Xa(i,o)),a}function No(s){var w,b,E,S;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let A=[],D=[...ah],R={};return t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(N=>D.push(`--${N}`)),t.chromeBinaryLocation&&(R.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&uh(t,A,D,null,c),lh(o,A,c),{logLevel:th,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:A,...R},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=QE(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.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"},...!lt.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Ku(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);lt.merge(h.desiredCapabilities,KE(t,r,n),JE(t,r,n),YE(t),XE(t,y,g),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((w=i.host)!=null&&w.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=jE(h,t,n,o,i,T,c,d);break;case"firefox":h=$E(h,t,c);break;case"safari":case"safari technology preview":h=FE(h,y);break;default:break}lt.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let A={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=_=>_[i.provider]||_[h.host]||_[A[h.host]],R=_=>{var $,V;return D(_)||_[($=h.desiredCapabilities)==null?void 0:$.browserName]||_[(V=h.desiredCapabilities)==null?void 0:V.version]||_||{}},N=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),k=R(R(N));Object.keys(k).length&&(ds.info(`Adding custom capabilities: ${JSON.stringify(k)}`),Object.assign(h.desiredCapabilities,k))}catch(A){ds.error("Failed to load custom capabilities",{error:A,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(UE(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let A=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),R=(E=D==null?void 0:D.capabilities)==null?void 0:E.alwaysMatch,N=_=>_.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(_=>{var $,V;R!=null&&R[_]&&(R[_].extensions=(V=($=A==null?void 0:A[_])==null?void 0:$.extensions)==null?void 0:V.map(N))}),R!=null&&R.loadExtension&&(R.loadExtension=(S=A==null?void 0:A.loadExtension)==null?void 0:S.map(N));let k=require("node:util");console.log(k.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var nh,Mo,ih,lt,oh,ds,th,zu,ah,Ju,Ku,UE,jE,rh,sh,WE,VE,GE,HE,qE,Yu=v(()=>{"use strict";nh=I(require("node:fs")),Mo=I(require("node:path")),ih=I(require("node:crypto")),lt=I(require("lodash"));F();de();W();le();ne();po();oh=require("lodash"),ds=x("testim-desired-capabilities-builder"),th=pi?"debug":"silent",zu={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"],Ju=(...s)=>ih.createHash("sha256").update(s.join("")).digest("hex"),Ku=s=>s.type===L.DEVICE_FARM||s.type===L.HYBRID&&s.provider==="devicefarm",UE=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=O.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ds.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};jE=lt.memoize(BE,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(lt.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Ju(o,a,l,r,c,i)}),rh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];sh={width:1920,height:1080},WE={width:1920,height:1200},VE={width:2560,height:1600},GE={width:2360,height:1770},HE={width:2048,height:1536},qE=new Set(["7","8","8.1","10","11"])});function Fe(s){var e,t,r,n,i,o,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((i=s.seleniumStack)==null?void 0:i.message)==="The arguments passed to a command are either invalid or malformed."||((o=s.message)==null?void 0:o.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function 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 Xu=v(()=>{"use strict"});function Qu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function i(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return i(y,f)}function o(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=i(u,"stroke-width");return!!g&&parseInt(g,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(u){return i(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Qu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||l(s))}var mh=v(()=>{"use strict"});var fh,gh,Wt,ZE,eS,Uo,hh=v(()=>{"use strict";fh=I(require("promise-queue")),gh=I(require("webdriverio"));de();$e();F();W();Fr();mh();Xu();us();Wt=x("WebDriverApi"),ZE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},eS={implicit:0,pageLoad:1,script:2},Uo=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,i=t?t.toString().slice(0,2e3):"";throw Wt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),tc!==void 0&&(e=tc);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(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,a,l,c,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),U("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(c=(l=e.capabilities.alwaysMatch)==null?void 0:l["goog:chromeOptions"])==null?void 0:c.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(Ce.GET_BROWSER);try{await this.addToQueue(async()=>{Wt.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),U("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await gh.remote(e),this.logGridStatus(r)}),U("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,Ce.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Wt.info("grid status is not supported by the grid",{testResultId:e});return}Wt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Wt.info("grid status",{gridStatusMsg:i.message,ready:i.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){Wt.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await o()}catch(a){if(Fe(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Fe(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ce.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,Ce.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ce.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Oe(e)))}finally{this.seleniumPerfStats.markEnd(t,Ce.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(Qu,{ELEMENT:e,[Gt]: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(),Wt))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let i=[];return i[eS[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(Fe(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Oe(e)),await this.elementIdValue(Oe(e),t)}async getViewportSize(e){let t=await this.execute(ZE);if(typeof e=="string"&&/(width|height)/.test(e)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Oe(e))})}submitFormManually(e){return this.addToQueue(async()=>{var i;let t=await((i=this.client)==null?void 0:i.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let i=await this.client.$(e);await this.client.action("pointer").move({origin:i}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,o),n=async()=>await this.client._setWindowSize(i,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(i){if(Fe(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Wt.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 Wt.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={};H(yh,{doubleClick:()=>tS});var tS,bh=v(()=>{"use strict";tS=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function f(w,b,E){return E>w&&E<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Mn={};H(Mn,{dispatchFocus:()=>rS});function rS(s,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function r(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let i=getLocatedElement(s);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Nn=v(()=>{"use strict"});var Sh={};H(Sh,{WebDriver:()=>xr});async function oS(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await nS(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var ms,vh,Eh,Be,sr,sS,Th,nS,Ar,iS,wh,Cr,xr,Un=v(()=>{"use strict";ms=I(require("lodash"));F();$e();Yu();vh=I(require("p-retry")),Eh=I(require("ua-parser-js"));Fr();W();Xu();hh();Y();le();us();Be=x("webdriver"),[sr,sS]=[0,2],{extractElementId:Th,getCdpAddressForHost:nS}=J,Ar=()=>(Te(),Me(Zt)).getSessionPlayer().codeSnippets,iS=()=>(Te(),Me(Zt)).getSessionPlayer().locatorBuilderUtils,wh=()=>(Te(),Me(Zt)).getSessionPlayer().utils,Cr=()=>(Te(),Me(Zt)).getSessionPlayer().positionUtils;xr=class extends Uo{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,E,S,A,D,R,N,k;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((S=(E=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:E.premiumFeatures)==null?void 0:S.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=No({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,w=u?()=>null:()=>this.executeJS("window.focus()");try{U("before initClient in webdriver.js init");let _=await this.initClient(y,i,d);U("after initResult before getCdpAddress in init"),this.cdpUrl=await oS(_),U("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ae(T),O.flags.dontFocusOnInit.isEnabled()||await w(),U("after focus and delay in webdriver.js init")}catch(_){let $=JSON.stringify(ms.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:_,capabilitiesAsString:$});let V=((D=(A=n==null?void 0:n.company)==null?void 0:A.activePlan)==null?void 0:D.plan)==="free";throw(R=_.stack)!=null&&R.includes("at startWebDriverSession")&&((N=_.message)!=null&&N.startsWith("Failed to create session"))&&((k=_.message)!=null&&k.includes("Timeout awaiting 'request'"))&&V?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(_.message)?new $r(_.message):/capabilit(y|ies)/.test(_.message)?new gi(_.message):/403 Forbidden/.test(_.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(_.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${_.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ms.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=re();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,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,[Gt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new hi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(Ce.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
24
|
-
var fn = ${
|
|
20
|
+
`))},uu=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:pu,argv:mu,exit:cu,cwd:xt}=global.process,Rv=new Set(["trace","debug","info","warn","error","silent"]);Oc(mu,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));du.description("Testim.io CLI").option("-h --help","output usage information",Df).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",Oe,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Oe,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Oe,[]).option("--test-id [test-id]","test ID to run",Oe,[]).option("-l, --label [label]","labels to search test by",Oe,[]).option("-n, --name [test-name]","test name to run",Oe,[]).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",Ev).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",Oe,[]).option("--test-plan-id [test-plan-id]","test plan to run",Oe,[]).option("--suite [suite-name]","suite to run",Oe,[]).option("--suite-id [suite-id]","suite ID to run",Oe,[]).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",Oe,[]).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(pu.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,lu.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,lu.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: ${uu.join("/")}`,Oe,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Oe,[]).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",Oe,[]).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)",Oe,[]).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)",Oe,[]).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(mu);p=du.opts(),Av=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},xv=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},kf=s=>{var r;if(!O.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=no.readFileSync(s);(r=Zl)!=null&&r.containsEncryptedCredentials(t.toString())&&Zl.injectProxyCredentialsStoreToGlobal()},Cv=async()=>{var y,T,v,b,E,S,A,D;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!mu.slice(2).length)throw Df(),new Fr;if(p.version){let R="Testim CLI Version: ";pu.npm_package_version&&(console.log(R,pu.npm_package_version),cu(0));let N=qe();N&&(console.log(R,N),cu(0)),console.log("Could not find version, please check the package.json manually"),cu(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Tm(),p.clearFileCache&&Kr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=Le.resolve(n);ym(R)}if(p.usePrefechedData&&wm(),p.playerRequirePath){let R=Le.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let N=Le.join(R,"tsconfig.node.json"),_=require("ts-node").register({project:N,ignore:[/node_modules/,new RegExp(`^${Bt.escapeRegExp(Le.relative(xt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:_.config.options.paths,baseUrl:_.config.options.baseUrl}),(Te(),Fe(Qt)).options.playerPath=R;let V=require("node:module"),z=V.prototype.require;V.prototype.require=function(pe){return pe==="rox-alias"?z.call(this,"rox-node"):pe==="canvas"?{}:z.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=no.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 x("missing --proxy option");if(bf(p))return Tf(p);try{let R={};p.configFile?(kf(p.configFile),R=require(Le.join(xt(),p.configFile)).config):p.optionsFile&&(R=require(Le.join(xt(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(N=>{let k=vv(N);p[k]=Sv(p[k],R[N])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let i=((y=p.testConfig)==null?void 0:y.length)||((T=p.testConfigId)==null?void 0:T.length),o=((v=p.testPlan)==null?void 0:v.length)||((b=p.testPlanId)==null?void 0:b.length),a=((E=p.suite)==null?void 0:E.length)||((S=p.suiteId)==null?void 0:S.length);if(p.seleniumCapsFile)try{r=require(Le.join(xt(),p.seleniumCapsFile))}catch(R){throw new x(`Failed to parse selenium caps file file error: ${R.message}`)}if((A=p.reporters)!=null&&A.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new x("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new x("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new x("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Le.join(xt(),p.chromeExtraPrefs))}catch(R){throw new x(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let N of R){let[k]=N.split("=");Pf.includes(k)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(N),k==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${k}), allowed values: ${JSON.stringify(Pf)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&kf(p.paramsFile),s={...s,...require(Le.join(xt(),p.paramsFile))}}catch(R){throw new x(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new x(`Failed to parse params string error: ${R.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new x("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(Av(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(Le.join(xt(),p.sauceOptions)),N=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let _=R.browserName.toLowerCase();switch(_){case"microsoftedge":p.browser="edge";break;default:p.browser=_}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let k=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!N&&p.browser==="chrome"&&k)throw new x("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new x(`Failed to parse saucelabs options file error: ${R.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new x("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(xv(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(Le.join(xt(),p.browserstackOptions)),N=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"),!N&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new x("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new x(`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(Le.join(xt(),p.perfectoOptions)),N={location:"US East",securityToken:p.perfectoToken};p.perfecto={...N,...R}}catch(R){throw new x(`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(Le.join(xt(),p.testobjectOptions)),N={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...N,...R}}catch(R){throw new x(`Failed to parse test object options file error: ${R.message}`)}if(!p.project){let N=await(await Promise.resolve().then(()=>(so(),au))).getProjectId();if(N)p.project=N;else throw new x("missing project-id info, either --login to provide new credentials or use --project <project-id>")}O.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=Math.max(p.browserTimeout,p.getSessionTimeout),p.driverRequestTimeout=Math.max(p.browserTimeout,p.driverRequestTimeout);let 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 N=await(await Promise.resolve().then(()=>(so(),au))).getToken();if(N)p.token=N;else throw new x("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 x("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new x("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new x("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new x("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 x("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new x("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new x("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new x("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 x(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...vr,...yn].includes(p.browser))throw new x(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new x("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!Rv.has(p.appiumLogLevel))throw new x(`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 x("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||i||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new x("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!o&&(p.beforeParallel!==1||p.afterParallel!==1))throw new x("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new x("please define exactly one of --grid or --grid-id or --host");if((D=p.host)!=null&&D.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Of.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(N=>N.trim()).filter(Boolean);let R=p.resultLabel.filter(N=>N.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&dr()&&p.resultLabel.unshift(dr()),R.length)throw new x("A result label cannot exceed 250 characters")}let u=Qi(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new x("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 x("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new x("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||o))throw new x("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&&!Bt.inRange(Bt.parseInt(p.setRetention),1,11))throw new x("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 f="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new x(`--mock-network-har ${f}`);if(p.mockNetworkPattern)throw new x(`--mock-network-pattern ${f}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new x("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new x("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new x("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new x("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Bt.difference(p.codeCoverageReporter,uu).length){let R=Bt.difference(p.codeCoverageReporter,uu);throw new x(`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 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"},g=Object.keys(h).filter(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&g.length){let R=g.length>1?"are":"is";throw new x(`${g.map(N=>h[N]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=no.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new x(`failed to parse field file error: ${R.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new x("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(Iv("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new x("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new x("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 x("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"},N=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...N}}catch(R){throw new x(`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 x("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"?dr():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,extensionPath:p.extensionPath,extensionLocation:[p.extensionPath].filter(Boolean),playerLocation:p.playerPath||u,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 jf={};H(jf,{installAllLazyDependencies:()=>_v,lazyRequire:()=>ot});async function ot(s,e={}){let t=Vc(s);if(t)return t;let r;e.silent||(r=(0,Uf.default)(`Installing ${s} before first usage...`).start());try{let n=await kv(s);return r&&r.succeed(),n}catch(n){Pv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Bf(s),o=`${s}@${i}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${o}`;throw r&&r.fail(c),n}}async function kv(s){return rs.has(s)||(rs.set(s,Ff(s)),rs.get(s).catch(()=>{rs.delete(s)})),rs.get(s)}async function Ff(s){let e=Vc(s);if(e)return e;let t=Bf(s),r=`${s}@${t}`;return await Mi(mt(),r),Jt(s)}async function _v(){let s=Object.keys(Za);for(let e of s)await Ff(e)}function Bf(s){let e=Object.entries(Za).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Uf,Pv,rs,bn=w(()=>{"use strict";Uf=I(require("ora"));Yr();W();F();ai();Ys();Pv=C("lazy-require"),rs=new Map});var Wf={};H(Wf,{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 Ft(async()=>{let t=await oe(s.testId,r=>ln({...e,testId:r}),{concurrency:2});return $f.keyBy(t,"testData.id")},"loadTests",Ov,[e,s.testId])()}var $f,Ov,io=w(()=>{"use strict";$f=I(require("lodash"));Kt();ge();F();Ov=1e3*60*60*10});var fu,Lv,ss,Vf,Gf,gu,Hf,qf=w(()=>{"use strict";F();Y();W();bn();fu=C("testimNgrok"),Lv=".whitelisted-ngrok.testim.io",ss="",Gf=async(s,e={})=>{if(!e.ngrokToken)throw new x("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${re()}-${s.projectData.projectId}${Lv}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let i=await(await ot("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(fu.info("replace https to http"),ss=i.replace("https://","http://")):ss=i,s.tunnelDiagnostics&&gu(),s.baseUrl=ss},gu=async(s=!0)=>{try{let t=(await ot("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===ss);console.log("ngrok stats",n),fu.info("ngrok stats",{tunnel:n})}catch(e){fu.error("error collecting ngrok stats",{err:e})}s&&(Vf=setTimeout(()=>gu(),1e4))},Hf=async s=>{if(!ss)return;clearTimeout(Vf),s.tunnelDiagnostics&&await gu(!1),await(await ot("ngrok")).disconnect(ss)}});var Zt,yu,zf,Mv,Nv,hu,oo,co,ao,Uv,Kf,Jf,Yf=w(()=>{"use strict";Zt=I(require("os")),yu=I(require("fs")),zf=I(require("child_process"));F();ge();Mv="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",Nv={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"}},hu=Zt.tmpdir(),oo=`${hu}/cloudflared`,co=null,ao=null,Uv=async()=>{if(await he(oo))return;let e=Nv[Zt.platform()+Zt.arch()];if(!e)throw new Error(`tunnel on ${Zt.platform()+Zt.arch()} platform is not supported.`);let t=e.extract?hu+e.path:oo;await Ke(`${Mv}/${e.path}`,t),e.extract&&await st(t,hu),await yu.promises.chmod(oo,"755")},Kf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Ol(s.company.companyId,t),Uv()]);co=r._id,ao=zf.spawn(oo,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Ll(s.company.companyId,co),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await yu.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 co&&e.push(Dl(s.company.companyId,co)),ao&&e.push(new Promise((t,r)=>{ao.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ao.kill()})),await Promise.all(e)}});function Xf(s,e){if(e){if(!Gv.includes(e)){wn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var Qf,Zf,jt,eg,tg,rg,lo,sg,wn,Bv,jv,vn,$v,Wv,Vv,se,Gv,uo=w(()=>{"use strict";Qf=I(require("ms")),Zf=I(require("p-retry")),jt=I(require("os")),eg=I(require("portfinder")),tg=I(require("child_process"));F();Ve();ge();rg=I(require("fs")),lo=I(require("fs/promises")),sg=require("path");Y();W();fn();ne();le();F();wn=C("lambdatestService"),Bv="https://downloads.lambdatest.com/tunnel/v3",jv={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"},vn=`${jt.tmpdir()}/LT`,$v=`${vn}/LT`,Wv=(0,Qf.default)("15m"),Vv="2560x1440",se=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===L.TESTIM_LAMBDATEST||e.type===L.LAMBDATEST||e.type===L.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){se.isLambdatestGrid(e)&&(se.lambdatestConfigPromise||=Il(),se.lambdatestConfig=await se.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Wv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await he($v))return;let t=jv[jt.platform()+jt.arch()];if(!t)throw new Error(`tunnel on ${jt.platform()+jt.arch()} platform is not supported.`);let r=`${vn}.zip`;await Ke(`${Bv}/${t}`,r),await st(r,vn)}static async chmodLtTunnel(e){if(!(jt.platform()==="win32"||!await he(e))){try{await lo.access(e,rg.constants.X_OK);return}catch{}try{await lo.chmod(e,"777")}catch(r){throw wn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ae(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){se.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await eg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;se.tunnelName=re();let c=["--tunnelName",se.tunnelName,"--infoAPIPort",String(t)];if(O.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(O.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Lc(u)])}if(O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new x("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 x("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await se.delay(3e3),await se.chmodLtTunnel((0,sg.join)(vn,"LT")),se.tunnel=tg.spawn("./LT",c,{cwd:vn});let d="",m="";se.tunnel.stdout.on("data",u=>{d+=u.toString()}),se.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}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});wn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),wn.error("Failed to start LT tunnel",{err:u}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!se.tunnel))return new Promise((t,r)=>{se.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),se.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,l){var T,v;if(!this.isActive)return{};let c=se.lambdatestConfig.CAPABILITIES[t]||{},d={...se.tunnelName&&{tunnel:!0,tunnelName:se.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:Xf(n,a==null?void 0:a.os)||Xf(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||se.lambdatestConfig.PLATFORM,resolution:se.lambdatestConfig.RESOLUTION??Vv,version:t==="safari"&&((v=o==null?void 0:o.lt)==null?void 0:v.safari_version)||c.version};if(l!==q.APPIUM&&l!==q.SELENIUM&&!f){let b=Ql({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&ke(h)&&(m=[...m,h]),m.length||wn.warn("No extension was loaded in LambdaTestService",{extUrls:b,extensionPath:h})}return O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&ke(g)&&(m=[...m,g]),{build:r,name:`${n} - ${i}`,selenium_version:se.lambdatestConfig.SELENIUM_VERSION,timezone:se.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},Gv=["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"]});var bu={};H(bu,{connect:()=>mo,disconnect:()=>fo,serveTunneling:()=>qv});var po,ng,ig,Hv,mo,fo,qv,Tu=w(()=>{"use strict";qf();mn();Yf();it();po=I(require("ora"));W();ne();uo();ng=C("tunnel"),ig=s=>{var e;return[L.TESTIM_LAMBDATEST,L.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Hv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===L.HYBRID&&s.gridData.tunnel==="cloudflare"},mo=async s=>{if(!s.tunnel)return;let e=br(),t;try{ig(s)?(t=(0,po.default)("Starting testim lambdatest tunnel...").start(),await se.connectTunnel(s)):Hv(s)?(t=(0,po.default)("Starting testim cloudflare tunnel...").start(),await Kf(s)):(t=(0,po.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 r.isInvalidCredsForLT&&(n="Could not connect to LambdaTest. Check your credentials and then try again."),ng.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
|
|
22
|
+
${r.stdoutResult}`:n)}},fo=async s=>{if(s.tunnel)try{ig(s)?await se.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)}},qv=async(s,e=new Promise(()=>{}))=>(await mo(s),es(()=>fo(s)),await e)});function zv(s){if(s.protocol)return s.protocol;if([L.TESTIM,L.BROWSERSTACK,L.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([L.TESTIM_ENTERPRISE,L.TESTIM_LAMBDATEST,L.DEVICE_FARM].includes(s.type)){let e=og.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function Kv(s){let e=og.exec(s);return e==null?void 0:e[3]}function ho(s){var E,S,A,D,R,N,k,_,$,V,z;let e=s&&Kv(s.host),t=s.port,r=s.path,n=s&&zv(s),i=s.token,o=s.slotId,a=(E=s.hybrid)==null?void 0:E.tunnel,l=(S=s.external)==null?void 0:S.user,c=(A=s.external)==null?void 0:A.key,d=s.type,m=d===L.HYBRID?a&&((N=(R=(D=s.hybrid)==null?void 0:D.external)==null?void 0:R[s.hybrid.tunnel])==null?void 0:N.user):l,u=d===L.HYBRID?a&&(($=(_=(k=s.hybrid)==null?void 0:k.external)==null?void 0:_[s.hybrid.tunnel])==null?void 0:$.key):c,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(V=s.mobileTokens)==null?void 0:V.androidToken,T=(z=s.mobileTokens)==null?void 0:z.iosToken,v=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:v,isSupportGrid:b}}async function Yv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(l){throw Xe.error("failed to get grid",{projectId:s,companyId:e,err:l}),new Error(ft.UNKNOWN)}if(Xe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Xe.error("invalid response - get grid",{res:o}),new Error(ft.UNKNOWN);if(o.status==="success"){if(o.grid.mode==="local")return{mode:"local"};((a=o.grid)==null?void 0:a.mode)==="custom"&&Object.assign(o.grid,ug(n));let l=ho(o.grid);return Jv(t,e,l.gridId,l.slotId,r,l.isSupportGrid),l}throw o.code==="not-found"?new et(ft.NOT_FOUND):o.code==="no-available-slot"?new Ht(`Failed to run test on ${r} - concurrency limit reached`):(Xe.error("invalid code error response - get grid",{res:o}),new et(ft.UNKNOWN))}function cg(s){return Sl(s)}async function lg(s,e,t){let n=(t||await cg(s)).find(i=>i._id===e);if(!n)throw new x(`Failed to find grid id: ${e}`);return ho(n)}async function Xv(s,e,t){let n=(t||await cg(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new x(`Failed to find grid name: ${e}`);return ho(n)}async function wu(s,e){let t=En[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete En[s],!a){if(!r){Xe.warn("failed to find grid slot id",{projectId:e});return}Xe.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await Tl(o,e,r,n,i)}catch(l){Xe.error("failed to release slot",{projectId:e,err:l})}}}async function Qv(s){let e=Object.values(En).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid){Xe.info("keep alive worker slots",{projectId:s,slots:e});try{await bl(s,e)}catch(t){Xe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function Zv(s){ag=global.setInterval(Qv,1e4,s)}async function eE(s){let e=Object.keys(En);if(e.length){Xe.warn("not all slots released before end runner flow",{projectId:s});try{await oe(e,t=>wu(Number(t),s))}catch(t){Xe.error("failed to release all slots",{err:t,projectId:s})}}}async function tE(s){await eE(s),clearInterval(ag)}function rE(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function sE(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function ug(s){let t=(()=>go.isEmpty(s.testobjectSauce)?go.isEmpty(s.saucelabs)?go.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=rE(t,s),l=sE(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:l,key:a,gridId:re()}}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:i,useChromeLauncher:o,gridId:a,grid:l}=s;if(n||o||i)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 Xv(c,l,e);if(Gs(s)||s.tunnelOnlyMode){Xe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new et("Missing host or grid configuration")}async function mg(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:l,localTmaUrl:c,useLocalChromeDriver:d,useChromeLauncher:m,company:u}=t,f=Boolean(d||m||c),h=u==null?void 0:u.companyId;return Yv(o,h,r,s,t,()=>vl({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:l,gridName:a,host:i,testResultId:n}))}var go,Xe,En,og,ag,Jv,Sn,fg,ns=w(()=>{"use strict";go=I(require("lodash"));ge();W();F();ne();Y();Xe=C("grid-service"),En={},og=/(^(https?):\/{2})?(.*)/,ag=null;Jv=(s,e,t,r,n,i)=>{En[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};Sn={start:Zv,end:tE};fg=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:i}={}}=s,{gridId:o,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!o||!a||((a===L.TESTIM_LAMBDATEST||a===L.LAMBDATEST)&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==L.HYBRID||!i||!l||!d||!m))return e;let u=await wl({companyId:i,gridId:o,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Xe.info("handling hybrid grid",{response:u,companyId:i});let f=ho({...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 vu(s,e,t){let r=is[s];if(!r)return;let{slotId:n}=r;if(delete is[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 jl(e,t,n)}catch(i){at.error("failed to release slot",{companyId:e,err:i})}}async function nE(s,e){let t=Object.values(is).filter(Boolean);if(t.length!==0){at.info("keep alive worker slots",{companyId:s,slots:t});try{await Wl(s,e,t)}catch(r){at.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function iE(s,e){gg=global.setInterval(()=>nE(s,e),1e4)}async function oE(s,e){let t=Object.keys(is);if(t.length){at.warn("not all slots released before end runner flow",{companyId:s});try{await oe(t,r=>vu(Number(r),s,e))}catch(r){at.error("failed to release all slots",{err:r,companyId:s})}}}async function aE(s,e){await oE(s,e),clearInterval(gg)}async function yg(s,e,t){let r;try{r=await Bl(s,e)}catch(n){throw at.error("failed to get slot",{companyId:s,err:n}),new Error(ft.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(ft.UNKNOWN);if(r.status==="success")return hg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new et(ft.NOT_FOUND):r.code==="no-available-slot"?new Ht("Failed to run test - concurrency limit reached"):(at.error("invalid code error response - get slot",{res:r}),new et(ft.UNKNOWN))}async function bg(s,e,t,r){let n=is[r];if(!n)throw new Error("slot not found");Object.assign(n,t),hg(r,n),await $l(s,e,n),at.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var at,is,gg,hg,Rn,os=w(()=>{"use strict";ge();W();F();ne();Y();at=C("slot-service"),is={},gg=null,hg=(s,e)=>{is[s]=e};Rn={start:iE,end:aE}});function xn(){return yo||"master"}function Tg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){yo="master";return}if(s!=null&&s.isArchived)throw new x(`Branch ${s.branch} is archived, run aborted.`);if(s){yo=s.branch||s;return}yo=e?"master":void 0}var yo,Eu=w(()=>{"use strict";Y()});var Cn,Su,cE,Iu,lE,bo,To,wo,vo,Eo,So=w(()=>{"use strict";F();ne();Cn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===me.FAILED},Su=s=>{let{status:e}=s;return e===me.ABORTED},cE=s=>{let{status:e}=s;return e===me.PASSED},Iu=s=>s.runnerStatus===xc.SKIPPED,lE=s=>s.testStatus===Je.EVALUATING,bo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Iu(t)&&(Ye(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,To=s=>Object.values(s).filter(e=>Cn(e)&&lE(e)).length,wo=s=>Object.values(s).filter(Cn),vo=s=>Object.values(s).filter(cE),Eo=s=>Object.values(s).filter(Su)});function pE(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Ru,Io,uE,Ro,vg=w(()=>{"use strict";Ru=I(require("lodash"));W();So();Io=C("debug-reporter"),uE=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],Ro=class{constructor(e){this.options=e}onTestStarted(e,t){Io.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;Io.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:l,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Ru.default.omit(this.options,uE),company:Ru.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let l=pE(process.argv);Io.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,i){let o=vo(e).length,a=Object.keys(e).length-o;Io.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Au,Ct,Pn=w(()=>{"use strict";ne();Au=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===L.DEVICE_FARM}},Ct=new Au});var Cu={};H(Cu,{Reporter:()=>dE});var er,kn,Er,Ao,Eg,xu,dE,Pu=w(()=>{"use strict";er=I(require("chalk")),kn=I(require("lodash"));F();ne();Pn();So();Er={success:er.default.green,warn:er.default.yellow,error:er.default.red},{CLI_MODE:Ao}=Nt,Eg="device",xu=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: ${er.default.underline(He(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?me.PASSED:me.FAILED,n=`(${e.testId})`,i=Er[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Ei(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=He(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(`
|
|
23
|
+
\r`)))}onTestPlanFinished(e,t,r,n,i){let o=wo(e),a=vo(e),l=Eo(e),c=a.length,d=l.length,m=o.length,u="",f="";if(Ct.isTestStatusEnabled){let v=To(e);u=` FAILED-EVALUATING: ${v}`,m-=v,f=` SKIPPED: ${bo(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=Er[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Ei(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=kn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=kn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=kn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=kn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let l=u=>{u.forEach((f,h)=>{var 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}${Ye(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(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Ao.APPIUM?Eg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Ao.APPIUM?Eg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${er.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===Ao.APPIUM?"device":"browser";if(n)console.log(Er.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(Er.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===Ao.APPIUM?"Appium":"Selenium";console.log(Er.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},dE=xu});var Ou={};H(Ou,{Reporter:()=>bE});function mE(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function fE(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 gE(s){return`${s.visitedUrlsJson||""}`}async function hE(s,e,t,r,n,i){function o(u){let f=He(s,t,u.testId,u.resultId,r),h={$:{name:mE(u),classname:n,time:Dc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(Cn(u)||Su(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=Cn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Iu(u)&&Ye(u,i)&&Ct.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=fE(u),h["visited-urls-json"]=gE(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},v={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(Ct.isTestStatusEnabled){v.skipped=bo(y,i);let b=To(y);v.failures-=b,v["failure-evaluating"]=b}return{$:v,testcase:Object.keys(y).map(b=>o(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return wo(u).length+Eo(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new _u.Builder().buildObject(m)}catch(u){return yE(u)}}function yE(s){let e=new _u.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 _u,Sg,ku,bE,Lu=w(()=>{"use strict";_u=I(require("xml2js"));F();Sg=require("fs");Pn();So();ku=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 hE(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Sg.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};bE=ku});var Ig={};H(Ig,{Reporter:()=>TE});function as(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 Du,Mu,TE,Rg=w(()=>{"use strict";W();Du=C("team-city-reporter");Mu=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 as(n)}onTestStarted(e,t,r,n){if(r){Du.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,i,o){if(i){Du.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${as(t)}' details='${as(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Du.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='${as(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${as(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${as(t)}']`)}},TE=Mu});var Ag={};H(Ag,{Reporter:()=>wE});var Nu,wE,xg=w(()=>{"use strict";Nu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},wE=Nu});var Cg={};H(Cg,{Reporter:()=>vE});var Uu,vE,Pg=w(()=>{"use strict";F();ru();Uu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=He(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return to(t)}},vE=Uu});var Fu,Q,Pt=w(()=>{"use strict";vg();Fu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new Ro(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Pu(),Cu));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Lu(),Ou));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Rg(),Ig)),r.includes("console")&&Promise.resolve().then(()=>(Pu(),Cu)),r.includes("junit")&&Promise.resolve().then(()=>(Lu(),Ou)),r.includes("json")&&Promise.resolve().then(()=>(xg(),Ag)),r.includes("chrome")&&Promise.resolve().then(()=>(Pg(),Cg))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,i){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var i;let n=t==null?void 0:t(...r);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||r))}}},Q=new Fu});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:i,companyName:o,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:i,companyName:o,projectName:a,companyPlan:l,source:kg(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);gt("test-run-ci",y)}function Lg({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let v=_g({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,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){gt("test-run-ci-success",v);return}gt("test-run-ci-fail",{...v,failureReason:n.failureReason})}catch(v){f.error("failed to update test end analytics",{err:v})}}function Dg(s){gt("batch-run-ci",s)}var kg,Bu=w(()=>{"use strict";ts();Gi();kg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Qr&&e?"ci-with-user":Qr?"ci":e?"cli-with-user":s});var Ng,xo,Ug=w(()=>{"use strict";Ng=require("istanbul-lib-report"),xo=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,ht,$g,Co,ju,Wg,EE,Vg,Gg,SE,IE,Hg,RE,AE,xE,CE,PE,qg,zg=w(()=>{"use strict";Fg=I(require("ora")),Bg=I(require("dayjs")),jg=I(require("test-exclude")),_n=I(require("fs")),ht=I(require("path")),$g=I(require("istanbul-reports")),Co=I(require("istanbul-lib-report"));ge();Y();F();W();bn();Ug();ju=C("test-run-status"),Wg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},EE=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)},SE=s=>s.substring(0,s.indexOf("?")),IE=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await ot("convert-source-map");if(t==="file"&&!e)throw new x("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Hg=(s,e)=>`${ht.resolve(s,Vg(e))}.js`,RE=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await oe(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await oe(i.sources,async(o,a)=>{if(Gg(r,o))return;let l=Hg(e,o);await _n.promises.mkdir(ht.parse(l).dir,{recursive:!0}),await _n.promises.writeFile(l,i.sourcesContent[a])})})},AE={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(EE(e)&&(e=SE(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=ht.dirname(this.getPath(s));return ht.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},xE=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=Co.createContext({dir:t,coverageMap:e,watermarks:Co.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 xo({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:AE}),$g.create(a,l).execute(o)}),i},CE=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await ot("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Gg(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},PE=async(s,e)=>{let{mergeProcessCovs:r}=await ot("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await Al(s,"testResult",`runId=${e}`)).data.docs;return await oe(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await cn(l,9e4);await oe(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await ll(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},qg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;ju.info("start js coverage process");let n=(0,Fg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=ht.resolve(s.codeCoverageReportPath||"./coverage"),o=ht.resolve(i,`.js/${(0,Bg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?ht.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([ot("istanbul-lib-coverage"),PE(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}ju.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await oe(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),v=await IE({sourceMapType:T,source:y,sourceMapDir:a});u[h]=v;let b=await CE(s,{source:y,sourceMap:v,functions:g});m.merge(b)}),await RE(s,o,u);let f=await xE(s,m,i,o);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof x?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),ju.error(c,{err:l})}}});var Kg={};H(Kg,{SELENIUM_PERF_MARKS:()=>Ae,SeleniumPerfStats:()=>Sr});var Ae,kE,Sr,cs=w(()=>{"use strict";F();Ae={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},kE=["ALL",...Object.values(Ae)],Sr=class{constructor(){this.marks=Object.fromEntries(kE.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=re();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,Ri(r,50)],[`${t}_P95`,Ri(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Qg={};H(Qg,{initServer:()=>LE,mapFilesToLocalDrive:()=>Wu});function Wu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Po[t.id]?{screenshot:Po[t.id]}:{})),Object.keys(ko).forEach(t=>{s.assets||={},s.assets[Xg[t]]=ko[t]}),s.assets||={},s.assets.screenshots=Object.values(Po)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function LE({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await ot("multer"),n=typeof t=="string"?t:_E;await $u.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=On.join(n,m.testResultId);try{await $u.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)}})}),o=(0,Yg.default)();o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(Po[d.stepId]=l.file.path),d.testResultId&&OE.includes(d.subType)&&(ko[d.subType]||=[],ko[d.subType].push(l.file.path)),c.sendStatus(200)}),o.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new x(`Port ${s} is already in use`));default:return c(u)}}})}var $u,Jg,On,Yg,_E,Po,ko,Xg,OE,Vu=w(()=>{"use strict";$u=I(require("fs")),Jg=I(require("os")),On=I(require("path")),Yg=I(require("express"));Y();bn();_E=On.join(Jg.tmpdir(),"testim/rca/"),Po={},ko={},Xg={"test-log":"consoleLogs","har-file":"networkLogs"},OE=Object.keys(Xg)});var tr,Gu,_o,Zg=w(()=>{"use strict";tr=I(require("lodash"));F();W();Gu=C("override-test-data-builder"),_o=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return tr.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)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Gu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Gu.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}Gu.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 tr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=re();return{...e,resultId:i,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Oo(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var Ir,Qe,DE,ME,NE,UE,Lo,eh=w(()=>{"use strict";Ir=I(require("lodash"));F();ne();ns();os();ge();Y();W();Pt();mn();zg();cs();Vu();de();le();Zg();Pn();Qe=C("test-run-status"),DE=dr(),ME=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,NE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,UE=qe();Lo=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Sr;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=Vs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:ui||t.parallel||1,browser:i,gitBranch:DE,gitCommit:ME,gitRepoUrl:NE,runnerVersion:UE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:v}=a,b={originalTestResultId:t,previousTestResultId:r,config:Ir.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:v},kl({projectId:n,runId:i,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,Q.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:i,projectData:o}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await zi(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let l=Ir.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,Tr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await Oo(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...i},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(i){throw Qe.error("Failed to start test",{err:i}),i}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Qe.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Je.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Je.EVALUATING} status`);return}if(c){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,He(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?me.PASSED:me.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Je.QUARANTINE}`)}monitorMemoryUsage(e){let t=Mc();t.isOverThreshold&&Qe.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&Wu(o,Qe),o.resultUrl=He(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Q.onTestFinished(o,e,i);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await Oo(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){Qe.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await Tr(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Qe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=kc;return e&&(n=i),Wr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g;let l=e.browser?qs(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Vr(O,n)&&Hs(a.nativeApp)&&!e.appId,d=zt(e)&&(Wr(a.nativeApp,n)||c),m=Ye(a,e)||d,u={testId:a.testId,status:m?me.SKIPPED:me.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Je.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await Rn.end(r,t),e==="mongo"&&await Sn.end(t)}async executionStart(e,t,r,n,i){Qe.info("execution started",{executionId:e});let{options:o}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=o;es(()=>Promise.all([this.endKeepAlive(d,t,c),Hi("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...O.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await Oo(o.beforeSuite,m),f=new _o(u,Ir.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let v=async()=>{let b=Ir.cloneDeep(this.testRunStatus);await oe(Object.keys(b),async A=>{var _;let D=b[A],R=(_=D.config)==null?void 0:_.testData,N=D.testId,k=await zi(t,N,A,R,l.defaults);k&&(delete D.config.testData,D.config.testDataUrl=k)});let E=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),S=ml({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:E,intersections:o.intersections});return this.executionStartedPromise=S,S.catch(A=>Qe.error(A)),S};try{await v()}catch(b){Qe.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Ir.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=Uc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===me.PASSED&&n++,m===me.SKIPPED&&i++,m===me.FAILED&&u===Je.EVALUATING&&o++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Oo(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Qe.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await qg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Hi("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Qe.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await dl(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function BE(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);us.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${zu(r)} current extension count: ${e.length}`),e.push(r)}}function uh(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;us.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=Do.basename(i));let l=Do.join(process.cwd(),a),c=ch(l);us.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${zu(c)} current extension count: ${e.length}`),e.push(c)}function jE(s,e,t,r,n,i,o,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...ah];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Hu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Hu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1,"profile.password_manager_leak_detection":!1},w3c:!0};qu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),qu(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"]=Hu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Cc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),lh(r,c,o),a===q.EXTENSION&&uh(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return se.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function WE(s,e,t){let r={"pdfjs.disabled":!0};return O.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 ls(s){return`${s.width}x${s.height}`}function KE(s){let{platform:e}=s;if(!e)return ls(sh);let t=e.split(" ")[1];return e.startsWith("Windows")&&zE.has(t)?ls(GE):e==="Linux"?ls(VE):e.startsWith("macOS")?ls(HE):ls(e==="OS X El Capitan"||e==="OS X Yosemite"?qE:sh)}function JE(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(n["sauce:options"].screenResolution=KE(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let i=(0,oh.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,ct.merge(i,n,r)}return ct.merge(n,r)}return{}}function YE(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 XE(s){return s.perfecto?s.perfecto:{}}function QE(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 ZE(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,i=r||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=Ya(i,o)),a}function Mo(s){var v,b,E,S;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let A=[],D=[...ah],R={};return t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(N=>D.push(`--${N}`)),t.chromeBinaryLocation&&(R.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&uh(t,A,D,null,c),lh(o,A,c),{logLevel:th,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:A,...R},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=ZE(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.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)}};qu(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);ct.merge(h.desiredCapabilities,JE(t,r,n),YE(t,r,n),XE(t),QE(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&&((v=i.host)!=null&&v.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=$E(h,t,n,o,i,T,c,d);break;case"firefox":h=WE(h,t,c);break;case"safari":case"safari technology preview":h=BE(h,y);break;default:break}ct.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let A={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=_=>_[i.provider]||_[h.host]||_[A[h.host]],R=_=>{var $,V;return D(_)||_[($=h.desiredCapabilities)==null?void 0:$.browserName]||_[(V=h.desiredCapabilities)==null?void 0:V.version]||_||{}},N=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),k=R(R(N));Object.keys(k).length&&(us.info(`Adding custom capabilities: ${JSON.stringify(k)}`),Object.assign(h.desiredCapabilities,k))}catch(A){us.error("Failed to load custom capabilities",{error:A,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(FE(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let A=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),R=(E=D==null?void 0:D.capabilities)==null?void 0:E.alwaysMatch,N=_=>_.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(_=>{var $,V;R!=null&&R[_]&&(R[_].extensions=(V=($=A==null?void 0:A[_])==null?void 0:$.extensions)==null?void 0:V.map(N))}),R!=null&&R.loadExtension&&(R.loadExtension=(S=A==null?void 0:A.loadExtension)==null?void 0:S.map(N));let k=require("node:util");console.log(k.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var nh,Do,ih,ct,oh,us,th,Hu,ah,zu,qu,FE,$E,rh,sh,VE,GE,HE,qE,zE,Ku=w(()=>{"use strict";nh=I(require("node:fs")),Do=I(require("node:path")),ih=I(require("node:crypto")),ct=I(require("lodash"));F();de();W();le();ne();uo();oh=require("lodash"),us=C("testim-desired-capabilities-builder"),th=li?"debug":"silent",Hu={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"],zu=(...s)=>ih.createHash("sha256").update(s.join("")).digest("hex"),qu=s=>s.type===L.DEVICE_FARM||s.type===L.HYBRID&&s.provider==="devicefarm",FE=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=O.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{us.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};$E=ct.memoize(jE,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(ct.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return zu(o,a,l,r,c,i)}),rh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];sh={width:1920,height:1080},VE={width:1920,height:1200},GE={width:2560,height:1600},HE={width:2360,height:1770},qE={width:2048,height:1536},zE=new Set(["7","8","8.1","10","11"])});function Ne(s){var e,t,r,n,i,o,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((i=s.seleniumStack)==null?void 0:i.message)==="The arguments passed to a command are either invalid or malformed."||((o=s.message)==null?void 0:o.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function 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 Ju=w(()=>{"use strict"});function Yu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function i(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return i(y,f)}function o(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=i(u,"stroke-width");return!!g&&parseInt(g,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(u){return i(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Yu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||l(s))}var mh=w(()=>{"use strict"});var fh,gh,$t,eS,tS,No,hh=w(()=>{"use strict";fh=I(require("promise-queue")),gh=I(require("webdriverio"));de();je();F();W();Ur();mh();Ju();cs();$t=C("WebDriverApi"),eS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},tS={implicit:0,pageLoad:1,script:2},No=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,i=t?t.toString().slice(0,2e3):"";throw $t.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),ec!==void 0&&(e=ec);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(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,a,l,c,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),U("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(c=(l=e.capabilities.alwaysMatch)==null?void 0:l["goog:chromeOptions"])==null?void 0:c.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(Ae.GET_BROWSER);try{await this.addToQueue(async()=>{$t.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),U("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await gh.remote(e),this.logGridStatus(r)}),U("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,Ae.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){$t.info("grid status is not supported by the grid",{testResultId:e});return}$t.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),$t.info("grid status",{gridStatusMsg:i.message,ready:i.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){$t.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await o()}catch(a){if(Ne(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Ne(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ae.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,Ae.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ae.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(_e(e)))}finally{this.seleniumPerfStats.markEnd(t,Ae.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(Yu,{ELEMENT:e,[Vt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ne(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(),$t))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let i=[];return i[tS[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(Ne(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(_e(e)),await this.elementIdValue(_e(e),t)}async getViewportSize(e){let t=await this.execute(eS);if(typeof e=="string"&&/(width|height)/.test(e)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(_e(e))})}submitFormManually(e){return this.addToQueue(async()=>{var i;let t=await((i=this.client)==null?void 0:i.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let i=await this.client.$(e);await this.client.action("pointer").move({origin:i}).perform()})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,o),n=async()=>await this.client._setWindowSize(i,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(i){if(Ne(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){$t.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return $t.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var yh={};H(yh,{doubleClick:()=>rS});var rS,bh=w(()=>{"use strict";rS=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function f(v,b,E){return E>v&&E<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Ln={};H(Ln,{dispatchFocus:()=>sS});function sS(s,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function r(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let i=getLocatedElement(s);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Dn=w(()=>{"use strict"});var Sh={};H(Sh,{WebDriver:()=>xr});async function aS(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await iS(r):void 0}catch(r){Ue.info("Error getting cdpAddress",r);return}}var ps,vh,Eh,Ue,rr,nS,Th,iS,Rr,oS,wh,Ar,xr,Mn=w(()=>{"use strict";ps=I(require("lodash"));F();je();Ku();vh=I(require("p-retry")),Eh=I(require("ua-parser-js"));Ur();W();Ju();hh();Y();le();cs();Ue=C("webdriver"),[rr,nS]=[0,2],{extractElementId:Th,getCdpAddressForHost:iS}=J,Rr=()=>(Te(),Fe(Qt)).getSessionPlayer().codeSnippets,oS=()=>(Te(),Fe(Qt)).getSessionPlayer().locatorBuilderUtils,wh=()=>(Te(),Fe(Qt)).getSessionPlayer().utils,Ar=()=>(Te(),Fe(Qt)).getSessionPlayer().positionUtils;xr=class extends No{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,E,S,A,D,R,N,k;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((S=(E=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:E.premiumFeatures)==null?void 0:S.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Mo({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,v=u?()=>null:()=>this.executeJS("window.focus()");try{U("before initClient in webdriver.js init");let _=await this.initClient(y,i,d);U("after initResult before getCdpAddress in init"),this.cdpUrl=await aS(_),U("after getCdpAddress in webdriver.js init"),Ue.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ae(T),O.flags.dontFocusOnInit.isEnabled()||await v(),U("after focus and delay in webdriver.js init")}catch(_){let $=JSON.stringify(ps.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Ue.error("failed to init webdriver",{err:_,capabilitiesAsString:$});let V=((D=(A=n==null?void 0:n.company)==null?void 0:A.activePlan)==null?void 0:D.plan)==="free";throw(R=_.stack)!=null&&R.includes("at startWebDriverSession")&&((N=_.message)!=null&&N.startsWith("Failed to create session"))&&((k=_.message)!=null&&k.includes("Timeout awaiting 'request'"))&&V?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(_.message)?new Br(_.message):/capabilit(y|ies)/.test(_.message)?new fi(_.message):/403 Forbidden/.test(_.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(_.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${_.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ps.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=re();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Ue.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Ue.warn("failed to click on alert",{err:l}));return}if(Ue.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Ue.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,[Vt]: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 gi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(Ae.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Ae.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
24
|
+
var fn = ${Rr().getLocatedElementCode};
|
|
25
25
|
return fn.apply(null, arguments);
|
|
26
|
-
`,t)}finally{this.seleniumPerfStats.markEnd(r,
|
|
27
|
-
var getLocatedElement = ${
|
|
26
|
+
`,t)}finally{this.seleniumPerfStats.markEnd(r,Ae.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,Ae.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...n){return await this.timeouts("script",r),await this.executeAsync(t,...n)}async markDynamicParent(t,r){function n({attributeName:i,attributeValue:o,locatedElement:a}){let l=getLocatedElement(a);if(!l)throw new Error("could not find dynamic parent");l.setAttribute(i,o)}await this.executeJS(`
|
|
27
|
+
var getLocatedElement = ${Rr().getLocatedElementCode};
|
|
28
28
|
var setDynamicParentAttribute = ${n.toString()};
|
|
29
29
|
return setDynamicParentAttribute.apply(null, arguments)
|
|
30
|
-
`,{attributeName:
|
|
31
|
-
const getLocatedElement = ${
|
|
30
|
+
`,{attributeName:oS().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(n){let i=getLocatedElement(n);if(!i)return null;let o=parseInt(window.getComputedStyle(i).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(i).paddingLeft.replace("px",""),10)||0,l=i.getBoundingClientRect();return{top:Math.round(l.top+o),left:Math.round(l.left+a)}}return this.executeJS(`
|
|
31
|
+
const getLocatedElement = ${Rr().getLocatedElementCode};
|
|
32
32
|
const getLocation = ${r.toString()};
|
|
33
33
|
return getLocation.apply(null, arguments)
|
|
34
34
|
`,t)}getElementLocationWithPadding(t){return this.getLocatedElementRectWithPadding(t)}getLocatedElementRect(t){function r(n){let i=getLocatedElement(n);if(!i)return null;let o=i.getBoundingClientRect();return{bottom:Math.round(o.bottom),height:Math.round(o.height),x:Math.round(o.left),right:Math.round(o.right),y:Math.round(o.top),width:Math.round(o.width)}}return this.executeJS(`
|
|
35
|
-
const getLocatedElement = ${
|
|
35
|
+
const getLocatedElement = ${Rr().getLocatedElementCode};
|
|
36
36
|
const getLocation = ${r.toString()};
|
|
37
37
|
return getLocation.apply(null, arguments)
|
|
38
|
-
`,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function r(i,o){function a(u){var h;return(h=u.childNodes)!=null&&h.length&&[...u.childNodes].filter(g=>g.nodeType===Node.ELEMENT_NODE).forEach(g=>{typeof g.tagName=="string"&&g.tagName.toLowerCase()==="title"?u.removeChild(g):a(g)}),u}function 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(o&&Array.prototype.some.call(u.children,y=>y.hidden)){let y=u.cloneNode(!0);return Array.prototype.filter.call(y.children,
|
|
39
|
-
const getLocatedElement = ${
|
|
38
|
+
`,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function r(i,o){function a(u){var h;return(h=u.childNodes)!=null&&h.length&&[...u.childNodes].filter(g=>g.nodeType===Node.ELEMENT_NODE).forEach(g=>{typeof g.tagName=="string"&&g.tagName.toLowerCase()==="title"?u.removeChild(g):a(g)}),u}function 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(o&&Array.prototype.some.call(u.children,y=>y.hidden)){let y=u.cloneNode(!0);return Array.prototype.filter.call(y.children,v=>v.hidden).forEach(v=>y.removeChild(v)),y.textContent.replace(/(\r\n|\n|\r)/gm,"")}return u.textContent.replace(/(\r\n|\n|\r)/gm,"")}function 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(i);return m?d(m):""}let{value:n}=await this.executeJS(`
|
|
39
|
+
const getLocatedElement = ${Rr().getLocatedElementCode};
|
|
40
40
|
const extractText = ${r.toString()};
|
|
41
41
|
return extractText.apply(null, arguments)
|
|
42
|
-
`,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var i,o;let r=
|
|
43
|
-
var getLocatedElement = ${
|
|
42
|
+
`,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var i,o;let r=Rr().getHtmlCode(void 0,t),n=this.seleniumPerfStats.markStart(Ae.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,Ae.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,Ae.GET_HTML);let l=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(o=(i=this.client)==null?void 0:i.requestHandler)!=null&&o.sessionID||Object.assign(l,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),l}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class i extends Error{}function o(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,vh.default)(async()=>{let{value:c}=await this.windowHandleSize(),{value:d}=await this.execute(o),m=c.width-d.screenWidth,u=c.height-d.screenHeight;await this.windowHandleSize({width:t.width+m,height:t.height+u});let{value:f}=await this.execute(o);if(f.screenWidth!==t.width||f.screenHeight!==t.height)throw new i},{retries:5-1,factor:1,minTimeout:0}).catch(c=>{if(!(c instanceof i))throw c});if(typeof t!="object"||typeof t.width!="number"||typeof t.height!="number"||r!==void 0&&typeof r!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(r===void 0?!0:r)?a():this.windowHandleSize(t)}setViewportSize(t,r){return this.setViewportSizeNEW({width:t,height:r},!0)}getBrowserMajorVersion(t){var r;try{return parseInt(((r=t.browser)==null?void 0:r.version)||"0",10)}catch(n){return Ue.error("failed to get browser version",{err:n}),0}}async getBrowserAndOS(){function t(a){let l=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(l[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(l[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";l=l[2]?[l[1],l[2]]:[a.appName,a.appVersion,"-?"];let c=a.match(/version\/(\d+)/i);return c!==null&&l.splice(1,1,c[1]),l[0].toLowerCase()}if(this.browserAndOS)return this.browserAndOS;function r(){var a;return(a=window==null?void 0:window.navigator)!=null&&a.userAgent?window.navigator.userAgent:"unknown"}let{value:n}=await this.executeJS(r),i=(0,Eh.default)(n),o=i.os;return this.browserAndOS={os:`${o.name} ${o.version}`,browserMajor:this.getBrowserMajorVersion(i),browser:t(n),userAgent:n,browserVersion:i.browser.version},this.browserAndOS}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:n,clickOffset:i}=t,o=Ar().calculateElementMiddlePoint(n),a=i.x,l=i.y;return!wh().isWithinBounds(n.left,n.left+n.width,o.x+a)||!wh().isWithinBounds(n.top,n.top+n.height,o.y+l)?(Ue.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,l,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:n,clickOffset:i}=t,o=n.left+i.x+r.x,a=n.top+i.y+r.y;return{x:o,y:a}}async actWithActionsAPI(t,r,n,i){let o=this.getRelativeMoveActions(t,n),a=this.getClickActions(i,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(a)}])}catch(l){Ue.error("tried to use element origin but failed because of visibility, trying absolute",l);let{x:c,y:d}=this.computeAbsoluteMovement(t),m=this.getMoveActions(c,d);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:m.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,rr,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(bh(),yh)),Promise.resolve().then(()=>(Dn(),Ln))]);return this.executeCodeAsync(`
|
|
43
|
+
var getLocatedElement = ${Rr().getLocatedElementCode};
|
|
44
44
|
var dispatchFocus = ${n.toString()};
|
|
45
45
|
var doubleClick = ${r.toString()};
|
|
46
46
|
var eventData = arguments[0];
|
|
47
47
|
var done = arguments[1];
|
|
48
48
|
return doubleClick.call(null, eventData, done);
|
|
49
|
-
`,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,
|
|
50
|
-
var res = requireOrImportMethod('${
|
|
49
|
+
`,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,rr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,nS,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(Ne(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(Ne(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 Ue.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:i,y:o,width:a,height:l}=n.value;return{x:r.left+i+a/2,y:r.top+o+l/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:i}=r.clickOffset;try{return await this.moveTo(t,n,i)}catch(o){if(Ne(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,n="viewport",i=0){return[{type:"pointerMove",duration:i,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){Ue.error("tried to use element origin but failed because of visibility, trying location",n);let i=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(i)}}getDragCoordinates(t){let r=t.filter(o=>o.event==="mousemove"||o.event==="pointermove"),n=r[0].pointerPosition,i=r.at(-1).pointerPosition;return{xDiff:i.screenX-n.screenX,yDiff:i.screenY-n.screenY}}async dragWithMoveTo(t,r,n,i,o){return await this.moveTo(t,i,o),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,i,o){let a=this.getMoveActions(i,o,t,1),l=this.getClickActions(["pointerDown"],rr),c=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],rr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(l).concat(c).concat(d)}])}async drag(t,r,n,i,o){let{width:a,height:l}=r,c=n-a/2+1,d=i-l/2,m=this.getDragCoordinates(o),{xDiff:u,yDiff:f}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,c,d);try{return await this.dragWithMoveTo(t,u,f,c,d)}catch(h){if(Ne(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,c,d);throw h}}getMoveRelativeSequence(t,r,n,i){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},l={x:n,y:i},c=10,d=Math.round(o(a,l)/c),m=Array.from({length:d},()=>({x:Math.round((l.x-a.x)/d),y:Math.round((l.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,i){return this.getMoveRelativeSequence(t,r,n,i).reduce((a,l)=>{let c=a.at(-1);return a.concat({x:Math.round(c.x+l.x),y:Math.round(c.y+l.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:i,fromX:o,fromY:a,toRect:l,toX:c,toY:d}=n,m=Ar().calculateElementMiddlePoint(i),u=Ar().calculateElementMiddlePoint(l),f=this.getMoveRelativeSequence(m.x+o,m.y+a,u.x+c,u.y+d);await this.moveTo(t,Math.floor(o),Math.floor(a)),await this.buttonDown();for(let h of f)await this.moveTo(null,h.x,h.y);return await this.moveTo(r,Math.round(c),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:l}=t,c=Ar().calculateElementMiddlePoint(r),d=Ar().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),T=this.getClickActions(["pointerDown"],rr),v=ps.flatMap(g,A=>this.getMoveActions(A.x,A.y)),b=this.getMoveActions(f,h),E=this.getClickActions(["pointerUp"],rr),S=y.concat(T).concat(v).concat(b).concat(E);return this.actions([{type:"pointer",id:"mouse",actions:S}])}async dragAndDrop(t,r,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,r,n)}catch(i){if(Ne(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw i}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(i){if(Ne(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw i}}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(i){if(Ne(i))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw i}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:l}=t,c=Ar().calculateElementMiddlePoint(r),d=Ar().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],rr);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],rr);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(Th(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(i){Ue.error("error getting element location",{err:i})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){Ue.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Ue.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(Ne(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var Xu,Qu,Nn,Zu=w(()=>{"use strict";W();le();ge();Xu=C("lab-features-service"),Qu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(Xu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await Rl(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){Xu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=O.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:i}=this,o=n.find(l=>l.featureFlagName===e),a=o==null?void 0:o.enabled;return Boolean(i&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw Xu.error(t,{featureFlagName:e.name}),new Error(t)}},Nn=new Qu});function cS(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function lS(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:r}=globalThis.require("path"),{promises:n}=globalThis.require("fs");return{sync:!1,lib:n.readFile(`${s}${t}package.json`).then(o=>{let a=JSON.parse(o);return import(r(s,a.main||`${t}index.js`))})}}}function uS(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function pS(s,e,t,r,n={},i=void 0,o=void 0){let a=Object.keys(n).map(h=>`
|
|
50
|
+
var res = requireOrImportMethod('${cS(n[h])}');
|
|
51
51
|
if (res.sync) {
|
|
52
52
|
var ${h} = res.lib;
|
|
53
53
|
} else {
|
|
@@ -110,7 +110,7 @@ ${r.stdoutResult}`:n)}},go=async s=>{if(s.tunnel)try{ig(s)?await se.disconnectTu
|
|
|
110
110
|
});
|
|
111
111
|
`,d=`
|
|
112
112
|
function injectCode(params, args, incomingParams, context, code) {
|
|
113
|
-
const constructWithArguments = ${
|
|
113
|
+
const constructWithArguments = ${uS.toString()}
|
|
114
114
|
|
|
115
115
|
const resolve = result => {
|
|
116
116
|
parentPort.postMessage({
|
|
@@ -176,7 +176,7 @@ ${r.stdoutResult}`:n)}},go=async s=>{if(s.tunnel)try{ig(s)?await se.disconnectTu
|
|
|
176
176
|
// A hack to fix an issue with stringified functions which use require. when compiling to JS, calls to require change to __require.
|
|
177
177
|
const __require = require;
|
|
178
178
|
const { parentPort } = require('worker_threads');
|
|
179
|
-
const requireOrImportMethod = ${
|
|
179
|
+
const requireOrImportMethod = ${lS.toString()}
|
|
180
180
|
|
|
181
181
|
// requireCode will set async to be true if needed.
|
|
182
182
|
${a}
|
|
@@ -185,7 +185,7 @@ ${r.stdoutResult}`:n)}},go=async s=>{if(s.tunnel)try{ig(s)?await se.disconnectTu
|
|
|
185
185
|
|
|
186
186
|
${c}
|
|
187
187
|
|
|
188
|
-
const isPromise = ${
|
|
188
|
+
const isPromise = ${fc.toString()}
|
|
189
189
|
|
|
190
190
|
parentPort.once('message', input => {
|
|
191
191
|
const { incomingParams, context, code } = input;
|
|
@@ -214,47 +214,47 @@ ${r.stdoutResult}`:n)}},go=async s=>{if(s.tunnel)try{ig(s)?await se.disconnectTu
|
|
|
214
214
|
injectCode(params, args, incomingParams, context, code);
|
|
215
215
|
});
|
|
216
216
|
})();
|
|
217
|
-
`,u=[],f=new
|
|
218
|
-
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",()=>{jo.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=ip.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=ip.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Fh.default)(()=>ce(n(),SS),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&jo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Bh={};H(Bh,{remoteStepServiceSocketIO:()=>IS});var ap,IS,jh=v(()=>{"use strict";op();ap=class extends bs{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))}},IS=new ap});var $h={};H($h,{remoteStepService:()=>Ts});var cp,jn,lp,Ts,$o=v(()=>{"use strict";Bo();ne();le();({REMOTE_STEP_SAVED:cp}=Rt),lp=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(jn=(await Promise.resolve().then(()=>(jh(),Bh))).remoteStepServiceSocketIO,jn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?bt.addFilter(`${e}:remoteStep`,{resultId:e},[cp]):jn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){bt.listenTo(`${e}:remoteStep`,[cp],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}jn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(bt.removeFilter(`${e}:remoteStep`,[cp]),Promise.resolve()):jn.unlistenToRemoteStep(e)}},Ts=new lp});var up,kr,Wh=v(()=>{"use strict";op();up=class extends bs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},kr=new up});var Gh={};H(Gh,{testResultService:()=>_t});var Vh,pp,_t,Wo=v(()=>{"use strict";Vh=require("events");Bo();ne();le();Wh();pp=class extends Vh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){bt.onConnect=()=>this.emit("socket-connected");return}kr.init(e),kr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?bt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Rt.TEST_RESULT_UPDATED,Rt.TEST_RESULT_CREATED]):kr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){bt.removeFilter(`${e}:testResult`,[Rt.TEST_RESULT_UPDATED,Rt.TEST_RESULT_CREATED]);return}await kr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){bt.listenTo(`${e}:testResult`,[Rt.TEST_RESULT_UPDATED,Rt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}kr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return kr.getSocket()}},_t=new pp});var qh,zh,Kh,ve,RS,Jh,Hh,AS,Vo,Yh=v(()=>{"use strict";qh=I(require("lodash"));F();de();$e();ss();ot();ge();Mh();zh=I(require("p-retry")),Kh=require("node:url");W();oo();us();ne();$o();Wo();ge();ve=x("test-run-handler"),RS=3,Jh=20*1e3,Hh=s=>JSON.stringify(s).length<Jh,AS="Test couldn't be started",Vo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Ir;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._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,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return zs(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?vi.FROM_DEVICE:vi.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 isTestRecordedWithEnhancedMode(){var t,r;let e=await pn({projectId:this._options.project,testId:this.testId,branch:this.branch});if(!((t=e==null?void 0:e.scenarioData)!=null&&t.steps))return!1;for(let n of e.scenarioData.steps){let i=(r=n==null?void 0:n.element)==null?void 0:r.mobileLocator;if((i==null?void 0:i.domMode)==="enhanced")return!0}return!1}async getRunRequestParams(){var r,n;let t={tokenV3:await At(),refreshToken:$i(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Td,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await Wi()};if(this._options.disableMockNetwork&&ht("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Hh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,l=this.testId;o?(Object.assign(t,{runData:i}),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 i=await vn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return 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 i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Hh(e))return;let r=async()=>{try{return await _l(this._options.project,this._testId,this._testResultId,e)}catch(o){return ve.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Pl(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===AS||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){U("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{U("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=o||{};U("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}),U("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 U("after Runtime.evaluate"),c.value}catch(o){throw ve.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Kh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){ve.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(ve.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await vr(a,l,d,c);n(m),r||setTimeout(o,3e3)}catch(m){ve.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else _t.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await vr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return ve.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw ve.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}catch(i){throw ve.error("failed to get test result after test start timeout",{err:i,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,o=>{if(this.isRetryKeyMismatch(o)){ve.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=qh.debounce(async()=>{try{await _t.joinToTestResult(this._testResultId,this.testId)}catch(o){ve.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await vr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(ve.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(ve.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return ve.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)_t.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Tl(this._testResultId,this._options.project,this.retryKey);a?await e()||(ve.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){ve.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&_t.off("socket-connected",e)}}listenToRemoteStep(e){Ts.listenToRemoteStep(this.testResultId,t=>{Dh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:RS;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=re(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Go,Xh=v(()=>{"use strict";Yh();Go=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Vo(e,t,l,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var CS,xS,PS,$n,dp=v(()=>{"use strict";os();cs();W();CS=x("worker-utils"),xS=async(s,e,t)=>{e&&await Eu(s,t)},PS=async(s,e,t)=>{await Su(s,e,t)},$n=async(s,e,t,r,n,i)=>{CS.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await xS(s,e,t),n==="redis"&&await PS(s,r,t)}}});function LS(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var qo,ey,zo,gp,ty,Tt,Qh,Zh,mp,Wn,kS,fp,_S,ir,OS,Ho,DS,Ot,Vn=v(()=>{"use strict";qo=I(require("ms")),ey=I(require("lodash")),zo=I(require("p-retry")),gp=I(require("dayjs")),ty=I(require("dayjs/plugin/duration"));F();$e();os();cs();ge();W();dp();kt();po();le();$o();Wo();ot();Ge();ne();Y();gp.default.extend(ty.default);Tt=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Qh,TEST_START_TIMEOUT_MSG:Zh,TEST_COMPLETE_TIMEOUT_MSG:mp}=Ue,{SETUP_TIMEOUT:Wn,NETWORK_ERROR:kS,GRID_ERROR:fp,BROWSER_CLOSED:_S,SELENIUM_ERROR:ir,UNKNOWN_ERROR:OS,MOBILE_SESSION_ERROR:Ho}=Gs;DS=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,i,o,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.lambdatestService=new se;this.id=0;this.uniqueId="";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,t.testResultId);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Us(!0)}async getBrowserOnce(e,t,r,n){throw new Us(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),Tt.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:me.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Hr(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=O.flags.increaseTDCRequestTimeout.isEnabled(),r=e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN,n=dr(O.flags.appiumConnectionRequestTimeout.getValue(),(0,qo.default)("2m")),i=dr(O.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===L.BROWSERSTACK||t&&r?o+(0,qo.default)("10m"):o+(0,qo.default)("1m")}getSessionTimeout(){if(Kt(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,zo.default)(async()=>{let n=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,zo.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await ce(yg(o,a,this.id),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof qt?Tt.info("could not get grid slot due to concurrency issue",r):Tt.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 i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{U("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);U("before getBrowserOnce retries");let l=this.options.getBrowserRetries-o;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,zo.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,U("before getBrowserOnce");let f=await ce(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Ue.GET_BROWSER_TIMEOUT_MSG);return U("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw Tt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof St)&&this.options.mode!==q.APPIUM&&await ae(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),U("after getBrowserOnce retries")}catch(o){throw await $n(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[St,$r].some(a=>o instanceof a)?o:o instanceof tt?new ur(o,fp):new ur(o,ir)}return n}async runTest(e,t,r){var d;U("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Kt(this.options)&&this.handleMobileTest(e);if(o)return o;U("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await At(),await this.runTestOnce(e,c)}finally{await $n(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 _,$;if(Xe(g,this.options)||Hr(O,(_=this.options.gridData)==null?void 0:_.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let w=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof ur,E=w(Zh),S=y&&(w(mp)||E&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||E)&&e.retryOnInfraErrors,R=S&&e.hasMoreTimeoutRetries(),N=e.hasMoreRetries()&&!b&&!S,k=!g.success&&(N||R||D);try{let V=e.retryKey;g.testRetryKey=V;let z=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,k,z),await this.runTestCleanup(),k){if(R&&await e.startNewTimeoutRetry(),D){Tt.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:y});let ee=($=this.options.projectData)==null?void 0:$.projectId,pe=e.testResultId,Lt=e.testId;await zi(ee,pe,Lt,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return N&&!D&&!R&&await e.startNewRetry(),Tt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:S,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(k)}t(this.id,...r);return}catch(V){if(V instanceof Ht)return;Tt.error("failed to process test result",{error:V}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
219
|
-
Please make sure the CLI has stable access to the internet. ${
|
|
220
|
-
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:ir,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:ir,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:ir,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:ir,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:OS,reason:w}},l=async g=>{var E;let y=await Ic();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),Tt.warn("error on run",{err:g});let T=(E=this.userData)==null?void 0:E.projectId,{errorType:w,reason:b}=this.options.mode===q.APPIUM?o(g):a(g,y);zi(T,this.testResultId,this.testId,{status:Vs.COMPLETED,success:!1,reason:b,errorType:w,testRetryKey:e.retryKey,setupStepResult:{status:Vs.COMPLETED,success:!1,reason:b,errorType:w}},e.remoteRunId),await n(LS(this.testId,this.testName,this.testResultId,b),g)},c=async g=>{var E;let y=this.testId,T=this.testResultId,w=(E=this.userData)==null?void 0:E.projectId,b=this.branch;if(!y||!T||!w||!b)return Tt.warn("Test failed. Not enough data to recover results via API",{err:g}),l(g);try{let S=await vr(y,T,w,b);if(Tt.warn("Test failed. Got results via API",{err:g,testResult:ey.default.omit(S,DS),resultId:T}),S&&S.status===Vs.COMPLETED&&!g.message.includes(mp))return await n(S);throw g}catch(S){return S!==g&&Tt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:w,branch:b,err:S}),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&&Ts.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),U("After onRunComplete"),t(this.id,...r)}catch(y){await c(y),t(this.id,...r)}finally{m||Ts.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 sy,ry,ws,hp=v(()=>{"use strict";F();sy=I(require("p-retry"));F();W();Y();ry=x("window-utils"),ws=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return ry.warn("selenium navigation failed. retrying to navigate",{err:i}),await ae(1500),r(n-1);throw!i.seleniumStack&&o&&ry.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};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,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await 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 window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&!r.href.startsWith("res://ieframe.dll/http_404.htm")&&!r.href.startsWith("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")}if(!(await this.driver.executeJS(e)).value)throw new St("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,sy.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var yp,vs,bp=v(()=>{"use strict";W();yp=x("cookies-utils"),vs=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 yp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw yp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw yp.error("failed to remove cookie",{err:t}),t}}}});var Tp,Ko,ny=v(()=>{"use strict";Tp=I(require("p-retry")),Ko=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[i,o]=await(0,Tp.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,Tp.default)(i,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function iy(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let i=s.offset||{top:0,left:0};if(i.top*=r,i.left*=r,!s.elementRect)return MS.warn("missing elementRect",ay.omit(s,"image")),{};let{elementRect:o}=s,a=await Jo.Jimp.fromBuffer(Buffer.from(n[1],"base64")),l=o.left*r+i.left*r,c=o.top*r+i.top*r,d=o.width*r,m=o.height*r;l<0&&(d+=l,d=Math.max(d,0),l=0),c<0&&(m+=c,m=Math.max(m,0),c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new wp("height or width is equal or lower than zero");return{elementImage:await a.crop({x:l,y:c,w:d,h:m}).getBase64(cy)}}async function NS(s,e){let t=new Jo.Jimp({width:s.width,height:s.height});for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await Jo.Jimp.fromBuffer(Buffer.from(i[1],"base64"));t.composite(o,n.position.left,n.position.top)}return await t.getBase64(cy)}function US(s,e){return NS(s,e)}async function FS(){}async function BS(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await FS(s[i]);return{key:i,url:o}}let r=await oe(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.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 ay,Jo,MS,cy,wp,Yo,ly=v(()=>{"use strict";ay=I(require("lodash"));F();Jo=require("jimp");W();MS=x("image-capture-utils"),cy="image/png",wp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Yo=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 iy(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 BS({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),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await iy({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await o(h.scrollPos,h.cropData);f.push(g)}return f}function l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,w=Array.from({length:Math.ceil(h/g)},(E,S)=>({scrollX:Math.min(S*g,h-g),cropX:S*g-Math.min(S*g,h-g),cropW:g-(S*g-Math.min(S*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(E,S)=>({scrollY:Math.min(S*T,y-T),cropY:S*T-Math.min(S*T,y-T),cropH:T-(S*T-Math.min(S*T,y-T))}));return w.flatMap(E=>b.map(S=>({scrollPos:{x:E.scrollX,y:S.scrollY},cropData:{top:S.cropY,left:E.cropX,width:E.cropW,height:S.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),US(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var uy,py,Xo,Qo,dy=v(()=>{"use strict";uy=I(require("p-retry")),py=I(require("semver"));F();W();hp();ny();ly();Te();Xo=x("tab-service"),Qo=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),Xo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=re();function l(c){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!c.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new ws(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Yo(t,a,new Ko(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=X(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),l=n(o),c=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=X();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(c=>i[c].url);if(this.exactUrlMatch(t,r,o))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,o,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){Xo.error("failed to get url or title",{err:i})}}catch(n){Xo.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(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){Xo.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let i=await this.waitForTabToOpen(e);await this.addNewTab(e,i,this.pendingTabs[e]),this.addFrameHandler(i),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,uy.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=py.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=X();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var vp,Zo,Ep=v(()=>{"use strict";vp=class{select(){return console.log(`
|
|
217
|
+
`,u=[],f=new xh.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:o}):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})}),i)}catch(h){if(!(h instanceof ie))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 dS(s){try{await Ih.promises.rm(s,{recursive:!0,force:!0})}catch(e){lt.warn("failed to remove install npm packages folder",{err:e})}}function Ch(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function ms(s,e,t,r,n,i){let o=Ch(n,e,s,t),{data:a}=await mS(o,r,i);return a}async function fs(s,e,t,r,n,i,o,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||O.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=xm(y.testimPackageLocalLocation);return[y.paramName,ds.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=Ch(o,n,e,i);if(c){let y=await cn(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 pS(u,t,r,s,m,a,l),nodeVersion:process.version}}async function mS(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Ph(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?n:ds.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Cm(o,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=Rm(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ds.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}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 ie&<.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Ph(){return ds.join(Rh.tmpdir(),"/testim_local_packages")}function fS(){let s=Ph();return dS(s)}var Ih,Rh,ds,Ah,xh,lt,gs=w(()=>{"use strict";Ih=I(require("fs")),Rh=I(require("os")),ds=I(require("path"));F();Yr();Ah=I(require("data-uri-to-buffer")),xh=require("worker_threads");Y();W();ge();Yr();le();lt=C("cli-service");fS().catch(s=>lt.warn("failed to clean local package folder",{err:s}))});var sr={};H(sr,{run:()=>hS});function gS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var hS,kh=w(()=>{"use strict";gs();Y();le();hS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await fs(r,n,i,o,a,l,c,d,m,u);return f&&gS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ie?new Error("Timeout while running action"):f}}});var ep={};H(ep,{run:()=>yS});var yS,_h=w(()=>{"use strict";gs();Y();yS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await ms(t,r,n,o,i,a),success:!0}}catch(l){if(l instanceof St)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof ie)return{success:!1,code:"timeout"};throw l}}});async function Lh(s,e,t,r){try{return await Cl(s,e,t,r)}catch{Uo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function TS(s,e,t,r,n){return Uo.info("finished to run remote step",{stepId:t,sessionId:n}),await Lh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Oh(s,e,t,r,n){return Uo.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Lh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Dh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),l=t.id;Uo.info("start play remote step",{stepType:o,stepId:l,sessionId:a});let c=bS[o];if(!c)return await Oh(n,r,l,`Failed to find step type ${o}`,a);try{let d=await c.run(e,t,i);return await TS(n,r,l,d,a)}catch(d){return await Oh(n,r,l,d.message,a)}}var Uo,bS,Mh=w(()=>{"use strict";kh();ge();_h();W();Uo=C("step-playback"),bS={"cli-validation-code-step":sr,"cli-wait-for-code-step":sr,"cli-action-code-step":sr,"cli-api-code-step":sr,"cli-condition-step":sr,"cli-download-code-step":sr,"node-package":ep}});var tp,Nh,Cr,vS,rp,yt,Fo=w(()=>{"use strict";F();it();tp=I(require("ws")),Nh=require("events");W();de();Cr=C("socket-service"),vS=5e3,rp=class extends Nh.EventEmitter{constructor(){super(...arguments);this.clientId=re();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Cr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),vS)}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(pd);return Rt().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new tp.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return Cr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{Cr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===tp.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Cr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Cr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Cr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(l){n(l)&&i(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=o.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=re(),l={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",c=>c.id===a,o),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},yt=new rp});var Fh,sp,ES,SS,IS,Uh,Bo,hs,np=w(()=>{"use strict";Fh=I(require("p-retry")),sp=I(require("socket.io-client"));de();F();W();ES=50,SS=10,IS=5e3,Uh=10*1e3,Bo=C("base socket service"),hs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Bo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Bo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===SS&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=ES)throw new Error(`Can't connect to Testim Servers.
|
|
218
|
+
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",()=>{Bo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout: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=sp.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=sp.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Fh.default)(()=>ce(n(),IS),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Bo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Bh={};H(Bh,{remoteStepServiceSocketIO:()=>RS});var ip,RS,jh=w(()=>{"use strict";np();ip=class extends hs{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))}},RS=new ip});var $h={};H($h,{remoteStepService:()=>ys});var op,Fn,ap,ys,jo=w(()=>{"use strict";Fo();ne();le();({REMOTE_STEP_SAVED:op}=It),ap=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Fn=(await Promise.resolve().then(()=>(jh(),Bh))).remoteStepServiceSocketIO,Fn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?yt.addFilter(`${e}:remoteStep`,{resultId:e},[op]):Fn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){yt.listenTo(`${e}:remoteStep`,[op],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Fn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(yt.removeFilter(`${e}:remoteStep`,[op]),Promise.resolve()):Fn.unlistenToRemoteStep(e)}},ys=new ap});var cp,Pr,Wh=w(()=>{"use strict";np();cp=class extends hs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Pr=new cp});var Gh={};H(Gh,{testResultService:()=>kt});var Vh,lp,kt,$o=w(()=>{"use strict";Vh=require("events");Fo();ne();le();Wh();lp=class extends Vh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){yt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?yt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[It.TEST_RESULT_UPDATED,It.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){yt.removeFilter(`${e}:testResult`,[It.TEST_RESULT_UPDATED,It.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){yt.listenTo(`${e}:testResult`,[It.TEST_RESULT_UPDATED,It.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},kt=new lp});var qh,zh,Kh,ve,AS,Jh,Hh,xS,Wo,Yh=w(()=>{"use strict";qh=I(require("lodash"));F();de();je();ts();it();ge();Mh();zh=I(require("p-retry")),Kh=require("node:url");W();io();cs();ne();jo();$o();ge();ve=C("test-run-handler"),AS=3,Jh=20*1e3,Hh=s=>JSON.stringify(s).length<Jh,xS="Test couldn't be started",Wo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Sr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._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?qs(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return Hs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Wr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?wi.FROM_DEVICE:wi.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 isTestRecordedWithEnhancedMode(){return(await ln({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await Rt(),refreshToken:ji(),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,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 $i()};if(this._options.disableMockNetwork&>("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Hh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,l=this.testId;o?(Object.assign(t,{runData:i}),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 i=await Tn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return 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 i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Hh(e))return;let r=async()=>{try{return await Pl(this._options.project,this._testId,this._testResultId,e)}catch(o){return ve.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),xl(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===xS||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){U("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{U("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=o||{};U("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}),U("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 U("after Runtime.evaluate"),c.value}catch(o){throw ve.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Kh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){ve.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(ve.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await wr(a,l,d,c);n(m),r||setTimeout(o,3e3)}catch(m){ve.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else kt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await wr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return ve.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw ve.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Me.TEST_START_TIMEOUT_MSG)}catch(i){throw ve.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Me.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await kt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ve.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||kt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){ve.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=qh.debounce(async()=>{try{await kt.joinToTestResult(this._testResultId,this.testId)}catch(o){ve.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await wr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(ve.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(ve.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return ve.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)kt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await yl(this._testResultId,this._options.project,this.retryKey);a?await e()||(ve.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){ve.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&kt.off("socket-connected",e)}}listenToRemoteStep(e){ys.listenToRemoteStep(this.testResultId,t=>{Dh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:AS;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=re(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Vo,Xh=w(()=>{"use strict";Yh();Vo=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Wo(e,t,l,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var CS,PS,kS,Bn,up=w(()=>{"use strict";ns();os();W();CS=C("worker-utils"),PS=async(s,e,t)=>{e&&await wu(s,t)},kS=async(s,e,t)=>{await vu(s,e,t)},Bn=async(s,e,t,r,n,i)=>{CS.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await PS(s,e,t),n==="redis"&&await kS(s,r,t)}}});function DS(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Ho,ey,qo,mp,ty,bt,Qh,Zh,pp,jn,_S,dp,OS,nr,LS,Go,MS,_t,$n=w(()=>{"use strict";Ho=I(require("ms")),ey=I(require("lodash")),qo=I(require("p-retry")),mp=I(require("dayjs")),ty=I(require("dayjs/plugin/duration"));F();je();ns();os();ge();W();up();Pt();uo();le();jo();$o();it();Ve();ne();Y();mp.default.extend(ty.default);bt=C("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Qh,TEST_START_TIMEOUT_MSG:Zh,TEST_COMPLETE_TIMEOUT_MSG:pp}=Me,{SETUP_TIMEOUT:jn,NETWORK_ERROR:_S,GRID_ERROR:dp,BROWSER_CLOSED:OS,SELENIUM_ERROR:nr,UNKNOWN_ERROR:LS,MOBILE_SESSION_ERROR:Go}=Ws;MS=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],_t=class{constructor(e,t,r,n,i,o,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.lambdatestService=new se;this.id=0;this.uniqueId="";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,t.testResultId);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Ms(!0)}async getBrowserOnce(e,t,r,n){throw new Ms(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),bt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Ye({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Vr(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=O.flags.increaseTDCRequestTimeout.isEnabled(),r=e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN,n=pr(O.flags.appiumConnectionRequestTimeout.getValue(),(0,Ho.default)("2m")),i=pr(O.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===L.BROWSERSTACK||t&&r?o+(0,Ho.default)("10m"):o+(0,Ho.default)("1m")}getSessionTimeout(){if(zt(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,qo.default)(async()=>{let n=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Me.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,qo.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await ce(yg(o,a,this.id),this.options.getBrowserTimeout,Me.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof Ht?bt.info("could not get grid slot due to concurrency issue",r):bt.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 i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{U("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);U("before getBrowserOnce retries");let l=this.options.getBrowserRetries-o;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,qo.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,U("before getBrowserOnce");let f=await ce(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Me.GET_BROWSER_TIMEOUT_MSG);return U("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw bt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof Et)&&this.options.mode!==q.APPIUM&&await ae(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),U("after getBrowserOnce retries")}catch(o){throw await Bn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Et,Br].some(a=>o instanceof a)?o:o instanceof et?new lr(o,dp):new lr(o,nr)}return n}async runTest(e,t,r){var d;U("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=zt(this.options)&&this.handleMobileTest(e);if(o)return o;U("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 Rt(),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 _,$;if(Ye(g,this.options)||Vr(O,(_=this.options.gridData)==null?void 0:_.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let v=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof lr,E=v(Zh),S=y&&(v(pp)||E&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||E)&&e.retryOnInfraErrors,R=S&&e.hasMoreTimeoutRetries(),N=e.hasMoreRetries()&&!b&&!S,k=!g.success&&(N||R||D);try{let V=e.retryKey;g.testRetryKey=V;let z=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,k,z),await this.runTestCleanup(),k){if(R&&await e.startNewTimeoutRetry(),D){bt.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:y});let ee=($=this.options.projectData)==null?void 0:$.projectId,pe=e.testResultId,Ot=e.testId;await qi(ee,pe,Ot,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return N&&!D&&!R&&await e.startNewRetry(),bt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:S,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(k)}t(this.id,...r);return}catch(V){if(V instanceof Gt)return;bt.error("failed to process test result",{error:V}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
219
|
+
Please make sure the CLI has stable access to the internet. ${Sc()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:v,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:E}=_c,S=g instanceof Error?g.message:g;return S.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),S.includes(Qh)||S.includes(b)?{errorType:jn,reason:"timeout while getting device"}:S.includes(T)||S.includes(E)?{errorType:Go,reason:"app doesn't exist on device"}:S.includes(v)?{errorType:Go,reason:"app never started, check app permission or app activity"}:S.includes(y)?{errorType:Go,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Go,reason:S}},a=(g,y)=>{let T=this.options.mode===q.APPIUM?"device":"browser";if(!y&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:_S,reason:i()};let v=g instanceof Error?g.message:g;if(v.includes(Qh))return{errorType:jn,reason:`Test couldn't get ${T}`};if(v.includes(Zh))return{errorType:jn,reason:"Test couldn't be started"};if(v.includes(pp)){if(!this.testRunTimeout)return{errorType:jn,reason:"Test timeout reached: test is too long"};let b=mp.default.duration({milliseconds:this.testRunTimeout}),E=Math.floor(b.asMinutes()),S=b.asSeconds(),A=E>0?` ${E} min`:"",D=S>0?` ${S} sec`:"";return{errorType:jn,reason:`Test timeout reached (timeout:${A}${D}): test is too long`}}if(g instanceof lr&&g.type){if(g.type===dp)return{errorType:dp,reason:`Test couldn't get ${T} from grid - ${g.message}`};if(g.type===nr)return{errorType:nr,reason:`Failed to create new session - ${g.message}`}}return"type"in g&&g.type===OS?{errorType:nr,reason:`Session terminated, this is often caused to connection
|
|
220
|
+
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:nr,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:nr,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:nr,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:nr,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:LS,reason:v}},l=async g=>{var E;let y=await Ec();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),bt.warn("error on run",{err:g});let T=(E=this.userData)==null?void 0:E.projectId,{errorType:v,reason:b}=this.options.mode===q.APPIUM?o(g):a(g,y);qi(T,this.testResultId,this.testId,{status:$s.COMPLETED,success:!1,reason:b,errorType:v,testRetryKey:e.retryKey,setupStepResult:{status:$s.COMPLETED,success:!1,reason:b,errorType:v}},e.remoteRunId),await n(DS(this.testId,this.testName,this.testResultId,b),g)},c=async g=>{var E;let y=this.testId,T=this.testResultId,v=(E=this.userData)==null?void 0:E.projectId,b=this.branch;if(!y||!T||!v||!b)return bt.warn("Test failed. Not enough data to recover results via API",{err:g}),l(g);try{let S=await wr(y,T,v,b);if(bt.warn("Test failed. Got results via API",{err:g,testResult:ey.default.omit(S,MS),resultId:T}),S&&S.status===$s.COMPLETED&&!g.message.includes(pp))return await n(S);throw g}catch(S){return S!==g&&bt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:v,branch:b,err:S}),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&&ys.joinToRemoteStep(this.testResultId),!d&&kt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==q.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),U("After onRunComplete"),t(this.id,...r)}catch(y){await c(y),t(this.id,...r)}finally{m||ys.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 sy,ry,bs,fp=w(()=>{"use strict";F();sy=I(require("p-retry"));F();W();Y();ry=C("window-utils"),bs=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return ry.warn("selenium navigation failed. retrying to navigate",{err:i}),await ae(1500),r(n-1);throw!i.seleniumStack&&o&&ry.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};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,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await 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 window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&!r.href.startsWith("res://ieframe.dll/http_404.htm")&&!r.href.startsWith("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")}if(!(await this.driver.executeJS(e)).value)throw new Et("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,sy.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var gp,Ts,hp=w(()=>{"use strict";W();gp=C("cookies-utils"),Ts=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 gp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw gp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw gp.error("failed to remove cookie",{err:t}),t}}}});var yp,zo,ny=w(()=>{"use strict";yp=I(require("p-retry")),zo=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[i,o]=await(0,yp.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,yp.default)(i,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function iy(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let i=s.offset||{top:0,left:0};if(i.top*=r,i.left*=r,!s.elementRect)return NS.warn("missing elementRect",ay.omit(s,"image")),{};let{elementRect:o}=s,a=await Ko.Jimp.fromBuffer(Buffer.from(n[1],"base64")),l=o.left*r+i.left*r,c=o.top*r+i.top*r,d=o.width*r,m=o.height*r;l<0&&(d+=l,d=Math.max(d,0),l=0),c<0&&(m+=c,m=Math.max(m,0),c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new bp("height or width is equal or lower than zero");return{elementImage:await a.crop({x:l,y:c,w:d,h:m}).getBase64(cy)}}async function US(s,e){let t=new Ko.Jimp({width:s.width,height:s.height});for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await Ko.Jimp.fromBuffer(Buffer.from(i[1],"base64"));t.composite(o,n.position.left,n.position.top)}return await t.getBase64(cy)}function FS(s,e){return US(s,e)}async function BS(){}async function jS(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await BS(s[i]);return{key:i,url:o}}let r=await oe(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.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 ay,Ko,NS,cy,bp,Jo,ly=w(()=>{"use strict";ay=I(require("lodash"));F();Ko=require("jimp");W();NS=C("image-capture-utils"),cy="image/png",bp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Jo=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 iy(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 jS({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),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await iy({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await o(h.scrollPos,h.cropData);f.push(g)}return f}function l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,v=Array.from({length:Math.ceil(h/g)},(E,S)=>({scrollX:Math.min(S*g,h-g),cropX:S*g-Math.min(S*g,h-g),cropW:g-(S*g-Math.min(S*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(E,S)=>({scrollY:Math.min(S*T,y-T),cropY:S*T-Math.min(S*T,y-T),cropH:T-(S*T-Math.min(S*T,y-T))}));return v.flatMap(E=>b.map(S=>({scrollPos:{x:E.scrollX,y:S.scrollY},cropData:{top:S.cropY,left:E.cropX,width:E.cropW,height:S.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),FS(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var uy,py,Yo,Xo,dy=w(()=>{"use strict";uy=I(require("p-retry")),py=I(require("semver"));F();W();fp();ny();ly();Te();Yo=C("tab-service"),Xo=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),Yo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=re();function l(c){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!c.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new bs(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Jo(t,a,new zo(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=X(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),l=n(o),c=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=X();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(c=>i[c].url);if(this.exactUrlMatch(t,r,o))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,o,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){Yo.error("failed to get url or title",{err:i})}}catch(n){Yo.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(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){Yo.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let i=await this.waitForTabToOpen(e);await this.addNewTab(e,i,this.pendingTabs[e]),this.addFrameHandler(i),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,uy.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=py.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=X();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var Tp,Qo,wp=w(()=>{"use strict";Tp=class{select(){return console.log(`
|
|
221
221
|
internal error - cant use port selector in selenium!!!!
|
|
222
|
-
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},
|
|
222
|
+
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Qo=new Tp});var Wn,Zo,ea=w(()=>{"use strict";hp();F();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"},Zo=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=zs;this.getLinksFromUnescapeHTML=Ks;this.cookieUtils=new Ts(this.driver)}get sessionPlayerInit(){return X()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,i=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-i.x,y:e.y-i.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function fy(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=my(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,i){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:l}=X();if(l.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw $S.error(u),new Error(u)}let c=await s.switchToLocatedFrame(a),d=my(c.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:c.value,frameLocateResultUrl:m}}async locate(r,n,i,o,a,l){let c=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${n}`;let d=await c.locate(r,i,r.targetId);d.isVisible=!0;let m=await c.handleLocateResult(d,l,r).catch(()=>{throw new Error("")}),{locatedElement:u}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},c.addFrameDataToContext&&c.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,i,o){let a=O.flags.enableFrameSwitchOptimization.isEnabled(),c=i.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=c&&c.stepId===r.id&&c.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),v=0;for(let b of T)v++,this.currentFrameHandler=await this.locate(b,v,this.currentFrameHandler,i,o,r);return this.currentFrameHandler}}let u=await o.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,i,o,r);return g}}return e}var $S,WS,my,gy=w(()=>{"use strict";W();le();Te();Ur();$S=C("frame-locator"),WS="ELEMENT",my=s=>s?s[WS]||s[Vt]:null});var ta,vp=w(()=>{"use strict";de();ta=()=>{try{if(ud)return!1;if(require("inspector").url())return!0}catch{}return!1}});var G,ue=w(()=>{"use strict";Te();G=class{constructor(e,t,r,n={},i=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=i;this.locateElementPlayer=o;this.exportsTest=a;this.frameId=0}get driver(){var e;return(e=this.context.project.defaults)!=null&&e.ignoreVisibilityForExisting&&!this.stepActionUtils.driver.getIgnoreVisibility()&&this.stepActionUtils.driver.setIgnoreVisibility(!0),this.stepActionUtils.driver}get sessionPlayerInit(){return X()}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 GS(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:O.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?O.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function HS(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 hy.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,i,o,a){let{locatorBuilderUtils:l,codeSnippets:c,visibilityUtils:d,positionUtils:m}=X();if(GS(n,d,m,s))return s.isVisible(e.seleniumElement);if(s.getIgnoreVisibility())return{visible:!0,invisibleReason:"visibility is ignored"};if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||l.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=c.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(S){throw kr.error("failed to execute getVisibilityCode",{err:S}),S}let{value:T}=y||{},v=T.elementVisibilityInfo||VS,[b,E]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(v,n,E,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=X();await s.execute(r(t))}}}var hy,kr,VS,Vn,yy=w(()=>{"use strict";ue();W();le();Te();hy=require("linkedom"),kr=C("locate-step-action"),VS={opacity:1,clientRects:{}};Vn=class extends G{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return HS(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 by={};H(by,{scroll:()=>qS});var qS,Ty=w(()=>{"use strict";qS=function(s,e,t,r,n,i,o,a){function l(v,b){if(!b)return{success:!1};elementScrollTo(b,v.x,v.y);let E=b.scrollLeft,S=b.scrollTop;return{success:Math.abs(S-v.y)<1&&Math.abs(E-v.x)<1,actualX:E,actualY:S}}function c(v,b){if(!t)return{x:n,y:i};let E=getLocatedElement(b);if(r&&!E)return{x:v.scrollWidth,y:v.scrollHeight};if(!E)throw new Error("could not find target element");let S=E.getBoundingClientRect(),A=0,D=0,R=Math.max(window.innerHeight-(S.height+10),0),N=Math.max(window.innerWidth-(S.width+10),0);return A=a?v.scrollTop+S.top-Math.min(i,R):v.scrollTop,D=o?v.scrollLeft+S.left-Math.min(n,N):v.scrollLeft,{x:Math.round(D),y:Math.round(A)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=c(m,e),h=l(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=c(m,e),h=l(f,m));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let v=T.getBoundingClientRect();g=v.left,y=v.top}return{success:h.success,actualX:g,actualY:y}}});var ra,wy=w(()=>{"use strict";ue();ra=class extends G{getFailureString(e,t,r,n,i){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${i}, x: ${n})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${i}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${n}`),o}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:i}}=this.sessionPlayerInit,o=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),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(()=>(Ty(),by)),d=`
|
|
223
223
|
const getLocatedElement = ${n.getLocatedElementCode};
|
|
224
224
|
const elementScrollTo = ${l.toString()};
|
|
225
225
|
const scroll = ${c.toString()};
|
|
226
226
|
return scroll.apply(null, arguments)
|
|
227
|
-
`;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var vy,Ey=v(()=>{"use strict";vy=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,l){e[t(a)]=l},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),i=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!i)throw new Error("to element not found");let o=function(a,l){let c=document.createEvent("CustomEvent");c.initCustomEvent(l,!0,!0,null),Object.assign(c,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(c):a.fireEvent&&a.fireEvent(`on${l}`,c)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var Sy,Iy=v(()=>{"use strict";Sy=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(k){e({status:"done",result:k,success:!0})}function a(k){k||={},e({status:"failed",result:k,success:!1,keep:!0})}function l(k){return k!=null&&k.toLowerCase?(k=k.toLowerCase(),k==="text"?"text/plain":k==="url"?"text/uri-list":k):k}function c(){try{return new DataTransfer}catch{return{data:{},setData(_,$){i[l(_)]=$},getData(_){return i[l(_)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(k){let _=k;for(;_&&_!==document.documentElement;){if(_.draggable)return _;_=_.parentElement}return null}function h(k,_,$){let V=_.element,{dispatchDragEventsOnClosestDraggable:z}=$;if(d.includes(k.type)&&z){if(!V&&_.lastDraggedElement)return _.lastDraggedElement;let ee=f(V);if(ee)return _.lastDraggedElement=ee,ee}return V}function g(k,_,$){function V(vt,Ur,P){return P>vt&&P<Ur}let z=k.pointerPosition||{};if(_)return{x:z.originX||0,y:z.originY||0};let ee=$.getBoundingClientRect(),pe=z.originX&&V(ee.left,ee.left+ee.width,z.originX)?z.originX:ee.left+ee.width/2,Lt=z.originY&&V(ee.top,ee.top+ee.height,z.originY)?z.originY:ee.top+ee.height/2;return{x:pe,y:Lt}}function y(k,_,$){let V=(_==null?void 0:_.modifiers)||{},z=g(k,$.isDrag,$.element),ee=(_==null?void 0:_.button)||0,pe=k.event;return m.includes(pe)?w(pe,V,z.x,z.y,ee):u.includes(pe)?E(pe,V,z.x,z.y):b(pe,V,z.x,z.y,ee)}function T(k,_,$){return{screenX:0,screenY:0,clientX:_,clientY:$,ctrlKey:Boolean(k.ctrl),altKey:Boolean(k.alt),shiftKey:Boolean(k.shift),metaKey:Boolean(k.meta),bubbles:!0,cancelable:!0,composed:!0}}function w(k,_,$,V,z){if(n){let pe=T(_,$,V);return pe.pointerType="mouse",pe.isPrimary=!0,new window.PointerEvent(k,pe)}let ee=document.createEvent("PointerEvent");return ee.initPointerEvent(k,!0,!0,document.defaultView,1,0,0,$,V,Boolean(_.ctrl),Boolean(_.alt),Boolean(_.shift),Boolean(_.meta),z,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),ee}function b(k,_,$,V,z){let ee=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return ee.initMouseEvent(k,!0,!0,document.defaultView,1,0,0,$,V,Boolean(_.ctrl),Boolean(_.alt),Boolean(_.shift),Boolean(_.meta),z,document.body?document.body.parentNode:document.documentElement),ee}function E(k,_,$,V){if(k==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let pe=document.createEvent("CustomEvent");return pe.initCustomEvent(k,!0,!0,null),Object.assign(pe,{dataTransfer:window.TSTA.dataTransfer}),pe}let z=T(_,$,V),ee=new window.DragEvent(k,z);return Object.defineProperties(ee,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),ee}function S(k,_,$){let V=h(k,_,$);V==null||V.dispatchEvent(k)}function A(k,_){function $(){return k.event==="click"&&_.isDrag&&!_.allEventsOnSameElement}return $()}function D(k,_,$){if($){let V=Math.min($.timeStamp-_.timeStamp,40);setTimeout(()=>{R(k)},V)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function R(k){let _,$=k.events[k.eventIndex],V=k.events[++k.eventIndex];try{k.element=getLocatedElement($.locatedElement),_=y($,s,k)}catch(z){return a(`exception in get event in drag step:${z.message}`)}if(A($,k))return D(k,$,V);if(_)try{S(_,k,$)}catch(z){return a(`exception in executeEvent in drag step:${z.message}`)}else return a(`cannot execute event ${$.event}`);D(k,$,V)}let N={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{R(N)}catch(k){a(k)}},0)}});var Ry={};H(Ry,{doClick:()=>qS});var qS,Ay=v(()=>{"use strict";qS=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,E){var D;function S(R){function N(){return i(R).find($=>[...$.classList||[]].includes("Select-control"))}function k(){let $=N();return $?$.querySelector("input"):null}let _=k();_==null||_.focus()}let A=(D=b.quirks)==null?void 0:D.isReactSelect;E.type==="mousedown"&&A&&S(b.element)}function n(b,E){var A;let S=(A=b.quirks)==null?void 0:A.isCKEditorFrame;E.type==="click"&&S&&document.body.focus()}function i(b){let E=[];for(;b!=null&&b.parentNode;)E.push(b),b=b.parentNode;return E}function o(b){let E={status:"done",result:b,success:!0,...w.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(E)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let E=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");E.initEvent("mouseover",!0,!0),b.dispatchEvent(E)}function c(b){let E={},S=b.getBoundingClientRect(),A=S.left+S.width/2,D=S.top+S.height/2,k=f("mousemove",E,A,D,0);b.dispatchEvent(k)}function d(b,E){function S(k,_,$){return $>k&&$<_}let A=b.pointerPosition||{},D=E.getBoundingClientRect(),R=A.originX&&S(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,N=A.originY&&S(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:R,y:N}}function m(b,E,S){return{screenX:0,screenY:0,clientX:E,clientY:S,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,E,S,A){if(!window.PointerEvent)return;let D=m(E,S,A);return D.pointerType="mouse",D.isPrimary=!0,new window.PointerEvent(b,D)}function f(b,E,S,A,D){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,S,A,Boolean(E.ctrl),Boolean(E.alt),Boolean(E.shift),Boolean(E.meta),D,document.body?document.body.parentNode:document.documentElement),R}function h(b,E){let S=["pointerup","pointerdown","pointermove"],A=E.modifiers||{},D=d(b,E.element),R=E.button||0,N=b.event;return S.includes(N)?u(N,A,D.x,D.y):f(N,A,D.x,D.y,R)}function g(){var E;let b=document.activeElement;for(;(E=b.shadowRoot)!=null&&E.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(E=>{try{return h(E,b)}catch{return}}).filter(Boolean).forEach(E=>{b.element.dispatchEvent(E),r(b,E),n(b,E)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let w={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!w.element){a("element not found");return}l(w.element),c(w.element);try{y(w);let b=g(),E=w.quirks,S=E==null?void 0:E.isReactSelect,A=E==null?void 0:E.isCKEditorFrame;!S&&!A&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var Cy={};H(Cy,{doDragPath:()=>zS});var zS,xy=v(()=>{"use strict";zS=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(b){e({status:"done",result:b,success:!0})}function o(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let E=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");E.initEvent("mouseover",!0,!0),b.dispatchEvent(E)}function l(b){let E={},S=b.getBoundingClientRect(),A=S.left+S.width/2,D=S.top+S.height/2,k=u("mousemove",E,A,D,0);b.dispatchEvent(k)}function c(b,E){function S(k,_,$){return $>k&&$<_}let A=b.pointerPosition||{};if(w.isDrag)return{x:A.originX||0,y:A.originY||0};let D=E.getBoundingClientRect(),R=A.originX&&S(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,N=A.originY&&S(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:R,y:N}}function d(b,E,S){return{screenX:0,screenY:0,clientX:E,clientY:S,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,E,S,A,D){if(r){let N=d(E,S,A);return N.pointerType="mouse",N.isPrimary=!0,new window.PointerEvent(b,N)}let R=document.createEvent("PointerEvent");return R.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,S,A,Boolean(E.ctrl),Boolean(E.alt),Boolean(E.shift),Boolean(E.meta),D,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),R}function u(b,E,S,A,D){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,S,A,Boolean(E.ctrl),Boolean(E.alt),Boolean(E.shift),Boolean(E.meta),D,document.body?document.body.parentNode:document.documentElement),R}function f(b,E){let S=["pointerup","pointerdown","pointermove"],A=E.modifiers||{},D=c(b,E.element),R=E.button||0,N=b.event;return S.includes(N)?m(N,A,D.x,D.y,R):u(N,A,D.x,D.y,R)}function h(b,E){function S(){return b.event==="click"&&E.isDrag&&!E.allEventsOnSameElement}return S()}function g(b,E,S){try{let A=f(E.events[b],E);h(A,E)||E.element.dispatchEvent(A)}catch{}if(b+1===E.events.length)S();else{let A=Math.min(E.events[b+1].timeStamp-E.events[b].timeStamp,n);setTimeout(()=>{g(b+1,E,S)},A)}}function y(b,E){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),E()})}let w={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!w.element){o("element not found");return}a(w.element),l(w.element),y(w,()=>{i()})}});var qn,na,Py=v(()=>{"use strict";qn=I(require("lodash"));ue();Ey();le();Iy();na=class extends G{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Ay(),Ry)),Promise.resolve().then(()=>(Nn(),Mn))]),c=`
|
|
227
|
+
`;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var vy,Ey=w(()=>{"use strict";vy=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,l){e[t(a)]=l},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),i=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!i)throw new Error("to element not found");let o=function(a,l){let c=document.createEvent("CustomEvent");c.initCustomEvent(l,!0,!0,null),Object.assign(c,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(c):a.fireEvent&&a.fireEvent(`on${l}`,c)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var Sy,Iy=w(()=>{"use strict";Sy=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(k){e({status:"done",result:k,success:!0})}function a(k){k||={},e({status:"failed",result:k,success:!1,keep:!0})}function l(k){return k!=null&&k.toLowerCase?(k=k.toLowerCase(),k==="text"?"text/plain":k==="url"?"text/uri-list":k):k}function c(){try{return new DataTransfer}catch{return{data:{},setData(_,$){i[l(_)]=$},getData(_){return i[l(_)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(k){let _=k;for(;_&&_!==document.documentElement;){if(_.draggable)return _;_=_.parentElement}return null}function h(k,_,$){let V=_.element,{dispatchDragEventsOnClosestDraggable:z}=$;if(d.includes(k.type)&&z){if(!V&&_.lastDraggedElement)return _.lastDraggedElement;let ee=f(V);if(ee)return _.lastDraggedElement=ee,ee}return V}function g(k,_,$){function V(wt,Nr,P){return P>wt&&P<Nr}let z=k.pointerPosition||{};if(_)return{x:z.originX||0,y:z.originY||0};let ee=$.getBoundingClientRect(),pe=z.originX&&V(ee.left,ee.left+ee.width,z.originX)?z.originX:ee.left+ee.width/2,Ot=z.originY&&V(ee.top,ee.top+ee.height,z.originY)?z.originY:ee.top+ee.height/2;return{x:pe,y:Ot}}function y(k,_,$){let V=(_==null?void 0:_.modifiers)||{},z=g(k,$.isDrag,$.element),ee=(_==null?void 0:_.button)||0,pe=k.event;return m.includes(pe)?v(pe,V,z.x,z.y,ee):u.includes(pe)?E(pe,V,z.x,z.y):b(pe,V,z.x,z.y,ee)}function T(k,_,$){return{screenX:0,screenY:0,clientX:_,clientY:$,ctrlKey:Boolean(k.ctrl),altKey:Boolean(k.alt),shiftKey:Boolean(k.shift),metaKey:Boolean(k.meta),bubbles:!0,cancelable:!0,composed:!0}}function v(k,_,$,V,z){if(n){let pe=T(_,$,V);return pe.pointerType="mouse",pe.isPrimary=!0,new window.PointerEvent(k,pe)}let ee=document.createEvent("PointerEvent");return ee.initPointerEvent(k,!0,!0,document.defaultView,1,0,0,$,V,Boolean(_.ctrl),Boolean(_.alt),Boolean(_.shift),Boolean(_.meta),z,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),ee}function b(k,_,$,V,z){let ee=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return ee.initMouseEvent(k,!0,!0,document.defaultView,1,0,0,$,V,Boolean(_.ctrl),Boolean(_.alt),Boolean(_.shift),Boolean(_.meta),z,document.body?document.body.parentNode:document.documentElement),ee}function E(k,_,$,V){if(k==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let pe=document.createEvent("CustomEvent");return pe.initCustomEvent(k,!0,!0,null),Object.assign(pe,{dataTransfer:window.TSTA.dataTransfer}),pe}let z=T(_,$,V),ee=new window.DragEvent(k,z);return Object.defineProperties(ee,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),ee}function S(k,_,$){let V=h(k,_,$);V==null||V.dispatchEvent(k)}function A(k,_){function $(){return k.event==="click"&&_.isDrag&&!_.allEventsOnSameElement}return $()}function D(k,_,$){if($){let V=Math.min($.timeStamp-_.timeStamp,40);setTimeout(()=>{R(k)},V)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function R(k){let _,$=k.events[k.eventIndex],V=k.events[++k.eventIndex];try{k.element=getLocatedElement($.locatedElement),_=y($,s,k)}catch(z){return a(`exception in get event in drag step:${z.message}`)}if(A($,k))return D(k,$,V);if(_)try{S(_,k,$)}catch(z){return a(`exception in executeEvent in drag step:${z.message}`)}else return a(`cannot execute event ${$.event}`);D(k,$,V)}let N={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{R(N)}catch(k){a(k)}},0)}});var Ry={};H(Ry,{doClick:()=>zS});var zS,Ay=w(()=>{"use strict";zS=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,E){var D;function S(R){function N(){return i(R).find($=>[...$.classList||[]].includes("Select-control"))}function k(){let $=N();return $?$.querySelector("input"):null}let _=k();_==null||_.focus()}let A=(D=b.quirks)==null?void 0:D.isReactSelect;E.type==="mousedown"&&A&&S(b.element)}function n(b,E){var A;let S=(A=b.quirks)==null?void 0:A.isCKEditorFrame;E.type==="click"&&S&&document.body.focus()}function i(b){let E=[];for(;b!=null&&b.parentNode;)E.push(b),b=b.parentNode;return E}function o(b){let E={status:"done",result:b,success:!0,...v.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(E)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let E=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");E.initEvent("mouseover",!0,!0),b.dispatchEvent(E)}function c(b){let E={},S=b.getBoundingClientRect(),A=S.left+S.width/2,D=S.top+S.height/2,k=f("mousemove",E,A,D,0);b.dispatchEvent(k)}function d(b,E){function S(k,_,$){return $>k&&$<_}let A=b.pointerPosition||{},D=E.getBoundingClientRect(),R=A.originX&&S(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,N=A.originY&&S(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:R,y:N}}function m(b,E,S){return{screenX:0,screenY:0,clientX:E,clientY:S,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,E,S,A){if(!window.PointerEvent)return;let D=m(E,S,A);return D.pointerType="mouse",D.isPrimary=!0,new window.PointerEvent(b,D)}function f(b,E,S,A,D){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,S,A,Boolean(E.ctrl),Boolean(E.alt),Boolean(E.shift),Boolean(E.meta),D,document.body?document.body.parentNode:document.documentElement),R}function h(b,E){let S=["pointerup","pointerdown","pointermove"],A=E.modifiers||{},D=d(b,E.element),R=E.button||0,N=b.event;return S.includes(N)?u(N,A,D.x,D.y):f(N,A,D.x,D.y,R)}function g(){var E;let b=document.activeElement;for(;(E=b.shadowRoot)!=null&&E.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(E=>{try{return h(E,b)}catch{return}}).filter(Boolean).forEach(E=>{b.element.dispatchEvent(E),r(b,E),n(b,E)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let v={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!v.element){a("element not found");return}l(v.element),c(v.element);try{y(v);let b=g(),E=v.quirks,S=E==null?void 0:E.isReactSelect,A=E==null?void 0:E.isCKEditorFrame;!S&&!A&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var xy={};H(xy,{doDragPath:()=>KS});var KS,Cy=w(()=>{"use strict";KS=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(b){e({status:"done",result:b,success:!0})}function o(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let E=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");E.initEvent("mouseover",!0,!0),b.dispatchEvent(E)}function l(b){let E={},S=b.getBoundingClientRect(),A=S.left+S.width/2,D=S.top+S.height/2,k=u("mousemove",E,A,D,0);b.dispatchEvent(k)}function c(b,E){function S(k,_,$){return $>k&&$<_}let A=b.pointerPosition||{};if(v.isDrag)return{x:A.originX||0,y:A.originY||0};let D=E.getBoundingClientRect(),R=A.originX&&S(D.left,D.left+D.width,A.originX)?A.originX:D.left+D.width/2,N=A.originY&&S(D.top,D.top+D.height,A.originY)?A.originY:D.top+D.height/2;return{x:R,y:N}}function d(b,E,S){return{screenX:0,screenY:0,clientX:E,clientY:S,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,E,S,A,D){if(r){let N=d(E,S,A);return N.pointerType="mouse",N.isPrimary=!0,new window.PointerEvent(b,N)}let R=document.createEvent("PointerEvent");return R.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,S,A,Boolean(E.ctrl),Boolean(E.alt),Boolean(E.shift),Boolean(E.meta),D,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),R}function u(b,E,S,A,D){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,S,A,Boolean(E.ctrl),Boolean(E.alt),Boolean(E.shift),Boolean(E.meta),D,document.body?document.body.parentNode:document.documentElement),R}function f(b,E){let S=["pointerup","pointerdown","pointermove"],A=E.modifiers||{},D=c(b,E.element),R=E.button||0,N=b.event;return S.includes(N)?m(N,A,D.x,D.y,R):u(N,A,D.x,D.y,R)}function h(b,E){function S(){return b.event==="click"&&E.isDrag&&!E.allEventsOnSameElement}return S()}function g(b,E,S){try{let A=f(E.events[b],E);h(A,E)||E.element.dispatchEvent(A)}catch{}if(b+1===E.events.length)S();else{let A=Math.min(E.events[b+1].timeStamp-E.events[b].timeStamp,n);setTimeout(()=>{g(b+1,E,S)},A)}}function y(b,E){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),E()})}let v={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!v.element){o("element not found");return}a(v.element),l(v.element),y(v,()=>{i()})}});var Gn,sa,Py=w(()=>{"use strict";Gn=I(require("lodash"));ue();Ey();le();Iy();sa=class extends G{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Ay(),Ry)),Promise.resolve().then(()=>(Dn(),Ln))]),c=`
|
|
228
228
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
229
229
|
var dispatchFocus = ${l.toString()};
|
|
230
230
|
var doClick = ${a.toString()};
|
|
231
231
|
var eventData = arguments[0];
|
|
232
232
|
var done = arguments[1];
|
|
233
233
|
return doClick.call(null, eventData, done);
|
|
234
|
-
`;try{return(d=(await this.driver.executeCodeAsync(c,n,o)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var l;let e=(l=this.step.events[0])==null?void 0:l.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),i=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=n?0:r.left+r.width/2-e.originX,a=i?0:r.top+r.height/2-e.originY;return{xOffset:o,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=
|
|
234
|
+
`;try{return(d=(await this.driver.executeCodeAsync(c,n,o)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var l;let e=(l=this.step.events[0])==null?void 0:l.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),i=this.isWithinBounds(r.top,r.top+r.height,e.originY),o=n?0:r.left+r.width/2-e.originX,a=i?0:r.top+r.height/2-e.originY;return{xOffset:o,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=Gn.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:n}=this.step,i=e.find(c=>["mousedown","pointerdown"].includes(c.event));if(i){let c=e.indexOf(i);e.splice(c,0,this.generateEventOfType(i,"mouseover"))}let{recordPointerMoveEvents:o=!1}=this.context.project.defaults||{},a=e.find(c=>c.event==="mouseup")||o&&e.find(c=>c.event==="pointerup"),l=Number(Gn.findLastIndex(e,c=>c.event==="mousemove")||o&&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 i=e.events,o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(Cy(),xy)),Promise.resolve().then(()=>(Dn(),Ln))]),c=`
|
|
235
235
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
236
236
|
var dispatchFocus = ${l.toString()};
|
|
237
237
|
var doDragPath = ${a.toString()};
|
|
238
238
|
return doDragPath.apply(null, arguments);
|
|
239
|
-
`;try{return(m=(await this.driver.executeCodeAsync(c,n,o)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset:n,rect:i}=e,o={frameOffset:{x:i.left-n.left,y:i.top-n.top},rect:n,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n)};if(O.flags.skipFileInputClicks.isEnabled()&&e.tagName==="INPUT"&&(e.elementSymbol.includes('type="file"')||e.elementSymbol.includes("type='file'")||e.elementSymbol.includes("type=file")))return{keep:!0,success:"skipped",reason:"Clicking on input type=file is disabled"};if(this.step.isDoubleClick){let d={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,d,o)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(O.flags.usePortedHtml5DragDrop.isEnabled()){let h=this.generateHTML5DragEventSequence(),g=this.context.data.timeToPlayStep+3e3,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},
|
|
239
|
+
`;try{return(m=(await this.driver.executeCodeAsync(c,n,o)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset:n,rect:i}=e,o={frameOffset:{x:i.left-n.left,y:i.top-n.top},rect:n,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n)};if(O.flags.skipFileInputClicks.isEnabled()&&e.tagName==="INPUT"&&(e.elementSymbol.includes('type="file"')||e.elementSymbol.includes("type='file'")||e.elementSymbol.includes("type=file")))return{keep:!0,success:"skipped",reason:"Clicking on input type=file is disabled"};if(this.step.isDoubleClick){let d={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,d,o)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(O.flags.usePortedHtml5DragDrop.isEnabled()){let h=this.generateHTML5DragEventSequence(),g=this.context.data.timeToPlayStep+3e3,y=this.getTarget(),T={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:h,eventData:{modifiers:this.step.modifiers,button:this.step.button},quirks:this.step.quirks,isDrag:this.step.isDrag,useRecordedMousedown:this.step.useRecordedMousedown,allEventsOnSameElement:this.step.allEventsOnSameElement,elementToFocusLocatedElement:y.elementToFocusLocatedElement,trackActiveElement:this.step.trackActiveElement,locatedElement:y.locatedElement,isRoot:y.isRoot},v=`
|
|
240
240
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
241
241
|
var dnd = ${Sy.toString()};
|
|
242
242
|
var eventData = arguments[0];
|
|
243
243
|
var done = arguments[1];
|
|
244
244
|
return dnd.call(null, eventData, done);
|
|
245
|
-
`;return this.driver.executeCodeAsync(
|
|
245
|
+
`;return this.driver.executeCodeAsync(v,g,T)}let u=`
|
|
246
246
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
247
247
|
var dnd = ${vy.toString()};
|
|
248
248
|
var eventData = arguments[0];
|
|
249
249
|
return dnd.call(null, eventData);
|
|
250
|
-
`,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=i=>i.fireOnTarget||["drop","dragenter"].includes(i.event);return e.forEach(i=>Object.assign(i,{locatedElement:n(i)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var
|
|
250
|
+
`,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=i=>i.fireOnTarget||["drop","dragenter"].includes(i.event);return e.forEach(i=>Object.assign(i,{locatedElement:n(i)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var Hn,ky=w(()=>{"use strict";ue();Hn=class extends G{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:i}}=this,o=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(o),{evaluatedText:l}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(l,a)?{success:!0}:{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(l),actual:a}}}catch{return{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:l.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var _y,JS,na,Oy=w(()=>{"use strict";_y=I(require("lodash"));ue();W();JS=C("evaluate-expression-step-action"),na=class extends G{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{JS.info("runner running incoming params evaluation");let i=t.incomingParams||{};_y.isEmpty(i)&&(i=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let o=["context",...i.as.functionParameters],a=[t,...i.as.functionArguments],c=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,o.concat([c]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(i){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:i.toString()},success:!1}}}}});var Ly={};H(Ly,{setText:()=>YS});var YS,Dy=w(()=>{"use strict";YS=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(){Ot()},window.addEventListener("unload",window.__unloadNavigator);let i=new Set(["keydown","keyup","keypress"]),o=15;function a(P){try{if(!t)return;let M=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return P.eventData&&(M.data=P.eventData.data),M}catch{}}function l(P){try{let M=document.createEvent("TextEvent");M.data=P.eventData.data;let j=1,K=P.eventData.locale||"en-US";return M.initTextEvent("textInput",!0,!0,window,P.eventData.data,j,K),M}catch{}}function c(P){return a(P)||l(P)}function d(P,M,j){try{return new KeyboardEvent(P,{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(P,M,j){try{let K=document.createEvent("KeyboardEvent");return K.initKeyEvent(P,!0,!0,null,Boolean(j.ctrl),Boolean(j.alt),Boolean(j.shift),Boolean(j.meta),M.key||"",0),K}catch{}}function u(P,M,j){try{let K=document.createEvent("Events");return K.initEvent(P,!0,!0),Object.assign(K,{altKey:Boolean(j.alt),ctrlKey:Boolean(j.ctrl),metaKey:Boolean(j.meta),shiftKey:Boolean(j.shift),keyCode:M.key||""}),K}catch{}}function f(P,M,j){return d(P,M,j)||m(P,M,j)||u(P,M,j)}function h(P){if(!i.has(P.event))return null;let M=P.eventData,j=M.modifiers||{},K=f(P.event,M,j);return Object.defineProperties(K,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(K,{_keyCode_:M.keyCode,_charCode_:M.charCode||0}),K}function g(P){return P.event==="textInput"?c(P):h(P)}function y(P,M){return(()=>{var K;return P.event==="textInput"&&!((K=M.quirks)!=null&&K.isAuth0Form)})()}function T(P,M){return P.event==="keyup"&&M.event==="keydown"?o:0}function v(P,M){let j=T(P,M);return Math.min(M.timeStamp-P.timeStamp,j)}function b(P){let M=Object.getOwnPropertyDescriptor(P,"value");if(!M)return;let j=P.value;P.value=`${j}#`,M.configurable&&delete P.value,P.value=j;let K=document.createEvent("HTMLEvents");K.initEvent("input",!0,!1),P.dispatchEvent(K),Object.defineProperty(P,"value",M)}function E(P){if(V(P.element))try{if(b(P.element),t)P.element.dispatchEvent(new Event("change"));else{let M=document.createEvent("HTMLEvents");M.initEvent("change",!1,!0),P.element.dispatchEvent(M)}}catch{}}function S(P,M,j){j?setTimeout(()=>{$(P)},v(M,j)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),E(P),Ot())}function A(P,M){return(P==="change"||P==="blur")&&M.element.tagName==="OPTION"}function D(P,M,j){return A(P.type,M)?M.element.parentElement:j.locatedElement?getLocatedElement(j.locatedElement):M.element}function R(P,M){let j=P.firstChild,K;for(;j;){if(j.nodeType===3){if(M.offset--<=0)return j}else if(j.nodeType===1&&(K=R(j,M),K))return K;j=j.nextSibling}return null}function N(P,M){if(!(!P||!M)){if(!isNaN(M.start))Object.assign(P,{selectionStart:M.start,selectionEnd:M.end});else if(!isNaN(M.nodeOffset)){let j;if(P.firstChild?j=R(P,{offset:M.nodeOffset}):j=P,j){let K=window.getSelection(),Ce=document.createRange();try{K.removeAllRanges(),Ce.setStart(j,M.textOffset),Ce.setEnd(j,M.textOffset),K.addRange(Ce)}catch{}}}}}function k(P,M){return P==="submit"&&Boolean(M.action)}function _(P,M,j){if(M.isFocusable&&M.isSelectable(P)&&P.type!=="submit")try{N(M.element,j.eventData.selection)}catch{}let K=D(P,M,j);if(!K)throw new Error("could not find element");k(P.type,K)?K.submit():K.dispatchEvent(P)}function $(P){let M,j=P.events[P.eventIndex],K=P.events[++P.eventIndex];try{M=g(j)}catch(Ce){return wt(`exception in get event in text step:${Ce.message}`)}if(y(j,P))return S(P,j,K);if(M)try{_(M,P,j)}catch(Ce){return wt(`exception in executeEvent in text step:${Ce.message}`)}else if(P.noEventExecuter)P.noEventExecuter(P,j);else return wt(`cannot execute event ${j.event}`);S(P,j,K)}function V(P){let M=P.tagName;return M==="INPUT"||M==="TEXTAREA"}function z(P){return P.getAttribute?Boolean(P.getAttribute("contenteditable")==="true"):!1}function ee(P,M){if(V(P.element)){P.element.value=M.eventData.text;let j=document.createEvent("Event");j.initEvent("input",!0,!1),P.element.dispatchEvent(j)}else P.isContentEditable&&(P.element.innerHTML=M.eventData.text)}function pe(){var M;let P=document.activeElement;for(;(M=P.shadowRoot)!=null&&M.activeElement;)P=P.shadowRoot.activeElement;return P}function Ot(P){let M={status:"done",result:P,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(M)}function wt(P){P||="";let M={status:"failed",result:P,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(M)}try{let P=V(n.element);n.isContentEditable=z(n.element),!P&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=P||n.isContentEditable,n.isSelectable=M=>M.type!=="keyup",n.noEventExecuter=ee}catch(P){wt(`exception in set text step:${P.message}`);return}let Nr=pe();dispatchFocus(s.elementToFocusLocatedElement,Nr),$(n)}});var ia,My=w(()=>{"use strict";ue();F();ia=class extends G{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(_e(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:i}=this,o=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:l}=i.codeSnippets;if(o.isDraftEditor&&l)return this.driver.executeJS(l(o.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let c={eventType:t,events:e,quirks:r,locatedElement:o.locatedElement,isRoot:o.isRoot,elementToFocusLocatedElement:o.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(Dy(),Ly)),Promise.resolve().then(()=>(Dn(),Ln))]),u=`
|
|
251
251
|
var getLocatedElement = ${i.codeSnippets.getLocatedElementCode};
|
|
252
252
|
var dispatchFocus = ${m};
|
|
253
253
|
var setText = ${d.toString()};
|
|
254
254
|
var eventData = arguments[0];
|
|
255
255
|
var done = arguments[1];
|
|
256
256
|
return setText.call(null, eventData, done);
|
|
257
|
-
`,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(
|
|
257
|
+
`,f=await this.driver.executeCodeAsync(u,a,c);return{success:Boolean((h=f.value)==null?void 0:h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(_e(t.seleniumElement),e[r]),r<e.length-1&&await 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(_e(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var Ny={};H(Ny,{runCode:()=>XS});var XS,Uy=w(()=>{"use strict";XS=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"),v=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||T||v){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let S={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(S)),T||v)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let i={},o={},a={},l=s.functionParams,c=s.transactionId;try{let m=r(s);m.push(i,o,a);let u=((d=s.function)==null?void 0:d.params)||l,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(c,{type:"promise"}),h.then(g=>{t(c,{status:"done",success:!0,result:{resultValue:g,exports:i,exportsTest:o,exportsGlobal:a}})},g=>{t(c,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:i,exportsTest:o,exportsGlobal:a}})})):t(c,{status:"done",success:!0,result:{resultValue:h,exports:i,exportsTest:o,exportsGlobal:a}})}catch(m){t(c,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:i,exportsTest:o,exportsGlobal:a}})}}});var oa,qn,ir,aa=w(()=>{"use strict";oa=I(require("lodash"));F();ue();W();le();qn=C("base-js-step-action"),ir=class extends G{isExceedingMaxResultSize(t,r){var n;try{let i=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,o=O.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>o;return i?a:(a&&qn.warn(`js result size exceeded ${o}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let n=`data-testim-${r}`;try{return window.sessionStorage.getItem(n)}catch(i){if(i.message.includes("sessionStorage")||i.message.includes("The operation is insecure")){let o=document.head.querySelector("#testim-storage-backup");return o?o.getAttribute(n):"{}"}throw i}},t)}constructJSFunParams(t){let r=t.incomingParams,n=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],i=[t.context,...r.as.functionArguments];return n.push(t.code),i.forEach(o=>{oa.isObject(o)&&Si(o,"seleniumElement",oa.isEqual)}),{function:{params:n,args:i},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:n,step:{id:i=""}}=this,o=r.config.retryTimeout,a=r.data.timeToPlayStep-o,l=async()=>{let c;try{c=await this.executeGetStatus(t)}catch(u){qn.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{qn.warn("non object value",{selRes:c}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===i);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-o<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=o,await ae(o),l()):{success:!0})};return l()}async executeInAut(t){let r=O.flags.experimentalPreCodeCompilation.isEnabled(),n=O.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(t),o=i.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=i.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
|
|
258
258
|
${t.code}
|
|
259
259
|
};`:`function(${m.join(",")}) {
|
|
260
260
|
${t.code}
|
|
@@ -264,18 +264,18 @@ Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: n
|
|
|
264
264
|
var eventData = arguments[0];
|
|
265
265
|
var funcToRun = ${a};
|
|
266
266
|
return runCode.call(null, eventData, funcToRun);
|
|
267
|
-
`;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:l}=t;i.exports&&(n.data.exports=i.exports);let c={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(
|
|
267
|
+
`;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:l}=t;i.exports&&(n.data.exports=i.exports);let c={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(qn.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),O.flags.useStepResultIdForStepTransactions.isEnabled()&&("stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:qn.warn("useStepResultIdForStepTransactions is enabled but stepResultId is not present in context",{step:t,context:r})),`${r.testResultId}:${n}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),i={transactionId:this.getTransactionId(t,r),id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(i);let o=await this.checkStatus(i.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var Wt,Fy=w(()=>{"use strict";aa();Wt=class extends ir{isFailedResult(e){return e===!1}}});var ws,By=w(()=>{"use strict";aa();ws=class extends ir{isFailedResult(e){return!e}}});var ca,jy=w(()=>{"use strict";ue();F();ea();ca=class extends G{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(_e(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(Wn[t]),this.setWithValueApi(e)}}});var la,$y=w(()=>{"use strict";ue();ea();la=class extends G{async performAction(){var i,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((i=this.step.keys)!=null&&i.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Wn[n])t.push(Wn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var Wy={};H(Wy,{selectOption:()=>QS});function QS(s,e){function t(r,n){let i=Element.prototype.matches,o=i&&isNativeFunction(i)?i:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(o=>{let a=document.createEvent("HTMLEvents");return a.initEvent(o,!0,!1),a}).forEach(o=>{if(e){n.dispatchEvent(o);return}r.dispatchEvent(o)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var Vy=w(()=>{"use strict"});var ua,Gy=w(()=>{"use strict";ue();F();le();ua=class extends G{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,i=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&i>=13&&!a)try{return await this.driver.elementIdClick(_e(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>(Vy(),Wy)),c=O.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
|
|
268
268
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
269
269
|
const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
|
|
270
270
|
const selectOption = ${l.toString()};
|
|
271
271
|
return selectOption.apply(null, arguments);
|
|
272
|
-
`;return(f=(await this.driver.executeJS(d,r,c)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var
|
|
272
|
+
`;return(f=(await this.driver.executeJS(d,r,c)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var pa,Hy=w(()=>{"use strict";ue();pa=class extends G{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var ZS,da,qy=w(()=>{"use strict";ue();ZS=(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(){}}),da=class extends G{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:n}=e,{width:i,height:o}=n,a=i/2,l=o/2,c=this.step.element.clickOffset;if(c&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:u}=c;this.sessionPlayerInit.utils.isWithinTargetRect(ZS(o,i,0,0),m,u)&&(a=m,l=u)}let d={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(l)}};return await this.driver.hover(t,d),{success:!0}}}});var zy={};H(zy,{wheel:()=>eI});var eI,Ky=w(()=>{"use strict";eI=function(s,e){function r(a,l){function c(h,g,y){return y>h&&y<g}let d=a.pointerPosition||{},m=l.getBoundingClientRect(),u=d.originX&&c(m.left,m.left+m.width,d.originX)?d.originX:m.left+m.width/2,f=d.originY&&c(m.top,m.top+m.height,d.originY)?d.originY:m.top+m.height/2;return{x:u,y:f}}function n(a,l,c){let d=r(a,c),m=(l==null?void 0:l.modifiers)||{},u={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:d.x,clientY:d.y,bubbles:!0,cancelable:!0,ctrl:Boolean(m.ctrl),alt:Boolean(m.alt),shift:Boolean(m.shift),meta:Boolean(m.meta)};return new WheelEvent("wheel",u)}function i(a,l){if(a.length===0){e({state:"success"});return}if(!l)throw new Error("element not found");let c=a.shift(),d=n(c,s.eventData,l),m=a[0]?Math.min(a[0].timeStamp-c.timeStamp,200):200;l.dispatchEvent(d),setTimeout(()=>{i(a,l)},m)}let o=getLocatedElement(s.locatedElement);i(s.events,o)}});var ma,Jy=w(()=>{"use strict";ue();ma=class extends G{async performAction(){var m;let{step:e,context:t}=this,{events:r,modifiers:n,button:i}=e;if(!(r!=null&&r.length))return;let o={events:r,eventData:{modifiers:n,button:i},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:l}=await Promise.resolve().then(()=>(Ky(),zy)),c=`
|
|
273
273
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
274
274
|
var wheel = ${l.toString()};
|
|
275
275
|
var eventData = arguments[0];
|
|
276
276
|
var done = arguments[1];
|
|
277
277
|
return wheel.call(null, eventData, done);
|
|
278
|
-
`;return{success:((m=(await this.driver.executeCodeAsync(c,a,o)).value)==null?void 0:m.state)==="success"}}}});var Yy={};H(Yy,{downloadFileAndFireDropEvent:()=>
|
|
278
|
+
`;return{success:((m=(await this.driver.executeCodeAsync(c,a,o)).value)==null?void 0:m.state)==="success"}}}});var Yy={};H(Yy,{downloadFileAndFireDropEvent:()=>tI});var tI,Xy=w(()=>{"use strict";tI=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let o=-1,a=0,l=[],c={endWithCallback:void 0,waitOn(){let d=++o;return function(m){d in l||(l[d]=m,a++,e.length===a&&c.endWithCallback(l))}},endWith(d){c.endWithCallback=d}};return c}function n(o,a,l){let c=new XMLHttpRequest;c.open("GET",o),c.responseType="blob",c.onload=function(){if(this.status>=200&&this.status<300)l({blob:c.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},c.onerror=function(){throw new Error("Failed to load blob")},c.send()}let i=r();e.forEach(o=>{n(o.url,o.name,i.waitOn())}),i.endWith(o=>{let a=createDropEvent(o);t.dispatchEvent(a)})}});var rI,fa,Qy=w(()=>{"use strict";ue();W();le();rI=C("drop-file-step-action"),fa=class extends G{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,i=this.getTarget(),o=O.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,o,rI),{downloadFileAndFireDropEvent:l}=await Promise.resolve().then(()=>(Xy(),Yy)),c=`
|
|
279
279
|
const getLocatedElement = ${e.getLocatedElementCode};
|
|
280
280
|
const createDropEvent = ${e.createDropEvent.toString()};
|
|
281
281
|
const downloadFileAndFireDropEvent = ${l.toString()};
|
|
@@ -322,7 +322,7 @@ Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: n
|
|
|
322
322
|
input.removeAttribute("disabled");
|
|
323
323
|
input.focus();
|
|
324
324
|
}
|
|
325
|
-
}`}async function
|
|
325
|
+
}`}async function nI(s,e){let t=null;try{t=(await vc(s)).body}catch(n){if(sI.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=`${Zy.tmpdir()}/${e}`;return await eb.promises.writeFile(r,t),r}function iI(s){return oe(s,e=>nI(e.url,e.name))}function oI(s,e){return e(s)}async function rb(s,e){let t=await iI(s),r=await oe(t,n=>oI(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var Zy,eb,sI,sb=w(()=>{"use strict";Zy=I(require("os"));Ve();eb=require("fs");F();W();sI=C("input-file-utils")});function cI(){return`async function downloadAndUpload(locatedElement, fileUrls) {
|
|
326
326
|
const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
|
|
327
327
|
const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
|
|
328
328
|
const attachTo = document.body || document.documentElement;
|
|
@@ -399,25 +399,25 @@ Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: n
|
|
|
399
399
|
element.dispatchEvent(new Event("change", { bubbles: true }));
|
|
400
400
|
}
|
|
401
401
|
element.removeEventListener("change", changeFiredHandler, true);
|
|
402
|
-
}`}var ha,
|
|
402
|
+
}`}var ga,ha,nb=w(()=>{"use strict";sb();ue();W();F();le();ga=C("input-file-step-action"),ha=class extends G{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){ga.info("workaround - stepaction - move element to visible position");let n=`
|
|
403
403
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
404
404
|
var getVisibleElement = ${tb(r)};
|
|
405
405
|
return getVisibleElement.apply(null, arguments);
|
|
406
|
-
`;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
|
|
406
|
+
`;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 ga.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let i="The element is not editable",o="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(i)||f.startsWith(o)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ga.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(_e(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=O.flags.overrideAzureStorageUrl.isEnabled(),n=O.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:l,driver:c}=this,d=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,l.testimServicesApi,r,ga);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await Mt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
|
|
407
407
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
408
|
-
const downloadAndUploadFile = ${
|
|
409
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await rb(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ba,Ta,ib=v(()=>{"use strict";ba=require("url");ue();Ta=class extends G{async updateBaseUrl(e){let t=new ba.URL(e),r=new ba.URL(this.context.recordedBaseUrl),n=new ba.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 wa,ob=v(()=>{"use strict";ue();F();wa=class extends G{async performAction(){await ae(this.step.durationMS||0)}}});var va,ab=v(()=>{"use strict";ue();va=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Jn,cb=v(()=>{"use strict";ue();Jn=class extends G{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ea,lb=v(()=>{"use strict";ue();Ea=class extends G{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var ub,Ip,Rp,pb=v(()=>{"use strict";ub=I(require("@applitools/spec-driver-webdriverio"));li();Te();Ip=class{constructor(){let{EyeSdkBuilder:e}=X(),t=cd["@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:ub.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=X(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Rp=new Ip});var mb,db,Yn,fb=v(()=>{"use strict";mb=I(require("lodash"));ue();W();pb();db=x("pixel-validation-step-action"),Yn=class extends G{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Rp.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"};mb.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),db.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){db.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Rp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ss,Ap=v(()=>{"use strict";ys();Y();ca();Ss=class extends or{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await hs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ie?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ar,gb=v(()=>{"use strict";Ap();ar=class extends Ss{isFailedResult(e){return e===!1}}});var Sa,hb=v(()=>{"use strict";Ap();Sa=class extends Ss{isFailedResult(e){return!e}}});var Ia,yb=v(()=>{"use strict";ys();ue();Y();Ia=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await gs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof It?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ie?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Or,bb=v(()=>{"use strict";ue();Or=class extends G{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,Tb=v(()=>{"use strict";ue();ye=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ra,wb=v(()=>{"use strict";ue();Ra=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Aa,vb=v(()=>{"use strict";ue();Aa=class extends G{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function cI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Ca(s,e){cI(lI,e),e.registerLocateStepActionUtils(Hn.getUtils(s))}var lI,Cp=v(()=>{"use strict";yy();wy();Py();ky();Oy();My();Fy();By();jy();$y();Gy();Hy();qy();Jy();Qy();nb();ib();ob();ab();cb();lb();fb();gb();hb();yb();bb();Tb();wb();vb();lI={locate:Hn,scroll:sa,mouse:na,submit:da,text:oa,"special-key":la,"user-code":Vt,"validation-code-step":Vt,"wait-for-code-step":Vt,"action-code-step":Vt,"condition-step":Es,"skip-code-step":Es,"element-code-step":Es,"evaluate-expression":ia,"text-validation":zn,"wait-for-text-validation":zn,"select-option":pa,"drop-file":ga,"input-file":ya,hover:ma,navigation:Ta,wheel:fa,sleep:wa,refresh:va,"keyboard-shortcut-step":ua,"api-validation":Jn,"api-action":Jn,"api-code-step":Vt,"extract-text":Ea,"simple-ui-verification":Yn,"wait-for-simple-ui-verification":Yn,"cli-validation-download-file":Or,"cli-wait-for-download-file":Or,"network-validation-step":Or,"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":Sa,"node-package":Ia,"email-code-step":Vt,"cli-email-code-step":ar,"sfdc-internal-test-step":Aa,"sfdc-recorded-step":Ra,"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 Eb,uI,Is,xp=v(()=>{"use strict";Eb=["simple-ui-verification","wait-for-simple-ui-verification"],uI=[...Eb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],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=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=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 Eb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var Ib={};H(Ib,{SeleniumTestPlayer:()=>Xn});var Sb,pI,Xn,Pp=v(()=>{"use strict";F();Sb=require("@applitools/eyes-sdk-core");Un();Y();W();bp();dy();Ep();ta();gy();Sp();Te();Cp();xp();pI=x("SeleniumTestPlayer"),Xn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Is(ra());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=X();this.driver=n??new xr;let d=new ea(this.driver);this.stepActionFactory=new c(d),Ca(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Qo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=fy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new vs(this.driver),FrameLocator:m,portSelector:Zo,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=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=X(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ie&&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(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var _p={};H(_p,{WorkerSelenium:()=>kp});function mI(s){let{playback:e}=X().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>U(`Got event ${t}`))}var xa,dI,kp,Op=v(()=>{"use strict";F();$e();Vn();W();kt();oo();ne();hp();Y();Pp();Te();ot();xa=x("worker-selenium"),dI=1e9,kp=class extends Ot{initPlayer(t){return new Xn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){U("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new ws(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),U("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),U("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,dI),await this.windowUtils.validatePageIsAvailable(),U("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 St||d||m?new St(`Page '${l}' is not available`):(xa.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Vi(),initializedFromCache:Gi()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=X(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Q.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),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await vn(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 ie&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(xa.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=o.maxKeepAliveGap();f>=3e4&&(xa.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),U("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),U("right after super.runTestOnce in workerSelenium");let u=await d();return U("right after runSeleniumTest"),u}catch(u){throw xa.error("failed to run test once",{err:u}),u}}}});var Rb,Ab,He,fI,gI,Lp,wt,Pa=v(()=>{"use strict";Rb=I(require("ora")),Ab=require("jimp");de();Ge();ge();W();ne();Te();le();He=x("mobile-grid-service"),fI="https://tdc.tricentis-cloud.com",gI="https://ui.headspin.io",Lp=class{constructor(){this.gridsAppIdGetter={[L.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[L.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[L.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[L.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[L.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[L.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===L.TESTIM_HEADSPIN?`${r||rc}/${nc}/devices`:t===L.TESTIM_TDC?`${r||sc}/${nc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:i})}catch(o){throw He.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw He.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Ws(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===L.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===L.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([L.BROWSERSTACK,L.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,l,c;if(t===L.TESTIM_HEADSPIN||t===L.TESTIM_TDC){let d=await Fl({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=X();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await wr(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),He.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=X(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await Ab.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/c.width,width:u,height:f}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ms}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?gI:fI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await be(`${e}/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:l}=t,c=await this.getTmaDeviceDetails(l,e);return await wr(a,n,i,o,"RUNNING",{device:c}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:c}),c}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(O.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await jl({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await dn({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/(Sd*60))+1)*60*1e3,Math.max(Ed,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[L.BROWSERSTACK]:{name:"Browserstack"},[L.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[L.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Rb.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 Bl({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:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===L.BROWSERSTACK||f===L.TESTIM_TVC||f===L.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Ms}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${ic}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?rc:sc}/${ic}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Id}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===L.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await vc({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,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await be(e,void 0,i)}},wt=new Lp});function Cb({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!==L.TESTIM_TDC&&e.type!==L.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function bI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function TI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&O.flags.enableBatchHeadSpin.isEnabled(),d=o&&(O.flags.enableBatchTDC.isEnabled()||O.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=O.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:bI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function ka(s){return"id"in s?s.id:s.packageName}function wI(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function vI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=wI(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":ka(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":ka(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:i=""}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:ka(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:ka(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function xb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o}){let a=TI(o.type,i,n);return vI({projectType:s,sessionCaps:a,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Oa({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 La({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===L.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?oc:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":oc:".*")}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 SI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",..._a(s,Rs)}}function Pb(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function II(s){return Pb(s,e=>e.startsWith("browserstack."),"browserstack.")}function RI(s){return Pb(s,e=>!e.startsWith("browserstack."))}function kb(s){return!s||!_b(s)?"2.0.0":s}function _b(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Ob({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=_b(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function _a(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}function AI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:l}){let{osVersion:c,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=EI(i,s),h=Oa({osVersion:c,mobileConfig:m}),g=La({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),y=qe(n.editorUrl,n.project,o.testId,o.testResultId,o.branch);if(u!==L.TESTIM_TVC&&l)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");let T={device:g,os_version:h,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":y,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Dr({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=O.flags.enableAppium2pCloudy.isEnabled(),g=Oa({osVersion:l,mobileConfig:d}),y=La({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),w={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...w,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Rd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=SI(b)),t="",Dr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Rs}})}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Oa({osVersion:l,mobileConfig:d}),f=La({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Lr.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Ob({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},w={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:kb(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,..._a(h,Rs),"sauce:options":{...T,...w,...(0,Lr.omit)(g,"appiumVersion")}};return Dr({projectType:s,sessionCaps:b,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return Dr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function PI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Oa({osVersion:l,mobileConfig:d}),f=La({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=II(n.browserstack),g=(0,Lr.omit)(RI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:w}=n.browserstack||{},b=O.flags.enableAppium2BrowserStack.isEnabled();if(b||Ob({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let S={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":kb(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},A={"appium:platformVersion":u,"appium:deviceName":f,..._a(g,Rs),"bstack:options":{...S,...(0,Lr.omit)(h,"appiumVersion")}};return Dr({projectType:s,sessionCaps:A,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let E={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:w||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,..._a(h,"browserstack.")};return Dr({projectType:s,sessionCaps:E,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function kI(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return xb(s);if(L.TESTIM_TVC===s.gridInfo.type)return AI(s);if(L.P_CLOUDY===s.gridInfo.type)return CI(s);if(L.SAUCELABS===s.gridInfo.type)return xI(s);if(L.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:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Lb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);Cb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=wt.getGridConnection(e),l=kI(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=_I(r,i==null?void 0:i.mobile);if(!(0,Lr.isEmpty)(T)){let w=Object.entries(T).map(([b,E])=>E.split(",").map(S=>S===".*"||S==="="?"":`${b}:${S}`).join(",")).join(" ").trim();l[`${y}:selector`]=w}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Dp.default)("2m"),f=(0,Dp.default)("12m"),h=dr(O.flags.appiumConnectionRetryCount.getValue(),m),g=dr(O.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function Db(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Cb({nativeAppMetadata:r,appPath:i,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 wt.getGridDirectConnection(t,d),f=xb({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Mb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Dr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function Nb(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 Dp,Lr,Rs,hI,Mp=v(()=>{"use strict";Dp=I(require("ms"));le();ne();Pa();Lr=require("lodash");F();de();Rs="appium:",hI=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var Da,Fb=v(()=>{"use strict";Da=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 Ma,Bb=v(()=>{"use strict";F();Ma=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 Np,Na,jb=v(()=>{"use strict";W();Np=x("mobile-frame-locator-mock"),Na=class{foundFrameCallback(){return Np.info("foundFrameCallback-mock invoked"),{}}locate(){return Np.info("locate-mock invoked"),{}}async findFrame(){return Np.info("findFrame-mock invoked"),{}}}});var OI,Wb,$b,As,Up=v(()=>{"use strict";OI=I(require("webdriverio")),Wb=require("@applitools/eyes-sdk-core");Fb();Ep();W();Bb();Sp();Te();Cp();jb();xp();$b=x("appium-test-player"),As=class{constructor(e,t,r,n=OI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=X(),m=new Ma(this.driver);this.stepActionFactory=new c(m),Ca(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Is(ra()),this.sessionPlayer=new a(e,{tabService:new Da,cookieUtils:void 0,FrameLocator:Na,portSelector:Zo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Wb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),$b.info("appium session deleted",{...i}))}catch(o){$b.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=X();e.off(o.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 Vb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function Gb(s){if((await LI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Hb=v(()=>{"use strict";Ge()});var qb={};H(qb,{WorkerLocalTma:()=>$p});var Mr,Fp,Bp,jp,$p,zb=v(()=>{"use strict";Ge();Mp();Vn();F();W();kt();Up();Te();Hb();Pa();Mr=x("worker-appium"),Fp=class extends Error{},Bp=class extends Error{},jp=class extends Error{},$p=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}=X(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var S;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await Gb(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:A}=await wt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:w,version:b},E]=await Promise.all([this.getAppStateFromDevice(o,a,T),Vb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Mr.info("device status and app state",{deviceStatus:E,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),Mr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let A={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(S=this.options.projectData)==null?void 0:S.name}-${this.options.project}`},D=Mb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),R={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:R,executionId:this.executionId,testResultId:this.testResultId});let N=await this.requestNewAppiumSessionFromTma(o,R,g);this.sessionData=N;let k=await m.attach({sessionId:N.sessionId,capabilities:D,options:{capabilities:D}});this.device=await wt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:k.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:k.capabilities})}catch(A){throw Mr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await 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=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new jp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await be(o)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Nt(n);await $s(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Bp(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Fp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=X(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var Jb={};H(Jb,{WorkerAppium:()=>Wp});var Kb,Nr,Wp,Yb=v(()=>{"use strict";F();Mp();Kb=require("linkedom");Vn();W();kt();Up();Te();Pa();ne();cs();Nr=x("worker-appium"),Wp=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,i){Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n,a=this.options.projectData.type,l=await wt.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=(a==="android"||a==="ios")&&await t.isTestRecordedWithEnhancedMode(),u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:m},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await wt.lockDevice(i,this.options.deviceUdid),h=await Db(f)):h=Lb(f),Nr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:d,capabilities:Nb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await o.remote(h),this.device=await wt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,m);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),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}=X(),n=async()=>{try{await t.getOrientation()}catch(i){Nr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&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){Nr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=X(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:E}=await wt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${E}`}else d=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Kb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Nr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await ce(u(),c)}catch(y){throw Nr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return`Testim/production:${ze()}`}}});var Ua,Xb=v(()=>{"use strict";F();Un();Y();Ua=class{constructor(e){this.id=e;this.driver=new xr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof ie&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Qb,Fa,Zb=v(()=>{"use strict";Qb=I(require("ws"));F();Fa=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 Qb.default(this._cdpUrl,{timeout:e}),r=zt(i=>{t.once("open",i)}),n=zt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var ja,Vp,Ba,eT=v(()=>{"use strict";F();ja=I(require("chrome-launcher"));Yu();Zb();gn();Vp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Fa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=No({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...ja.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await ja.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 fr(`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}},Ba=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new Vp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Gp={};H(Gp,{WorkerExtension:()=>Qn});function DI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function tT(s){return DI(s)?s:new Error(s)}var pt,Qn,$a=v(()=>{"use strict";$e();Y();Vn();F();W();kt();ne();Xb();eT();ot();pt=x("worker-ext"),Qn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Ba(this.id):new Ua(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw pt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Vi(),initializedFromCache:Gi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;U("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ie))throw u;return pt.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 pt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(U("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw pt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ie))throw T;pt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),pt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=Gs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),w=await yc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(S){pt.error("Could not update the grid about the test status",{err:S})}m.isAlive()||(pt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(pt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw pt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),tT(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw pt.warn("failed to start url",{err:h}),tT(h)}};t.driver.start();try{return await super.runTestOnce(e,t),U("WorkerExtension super.runTestOnce"),await c()}catch(d){throw pt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var qp={};H(qp,{WorkerExtensionSingleBrowser:()=>Hp});var MI,NI,Hp,zp=v(()=>{"use strict";$e();F();W();dp();kt();$a();MI=x("base-worker"),NI=500,Hp=class extends Qn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await $n(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,i){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(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 i=this.handleQuarantine(t);if(i)return i;U("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ae(NI)}}});var Kp,Wa,rT=v(()=>{"use strict";Un();de();$e();$u();ot();tp();Y();W();ne();Xh();eo();Kp=x("worker-manager"),Wa=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(Op(),_p))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(zb(),qb))).WorkerLocalTma:(await Promise.resolve().then(()=>(Yb(),Jb))).WorkerAppium;default:return Fn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(zp(),qp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>($a(),Gp))).WorkerExtension}else switch(r){case(Er.find(n=>n===r)&&Fn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(zp(),qp))).WorkerExtensionSingleBrowser;case Er.find(n=>n===r):return(await Promise.resolve().then(()=>($a(),Gp))).WorkerExtension;case Tn.find(n=>n===r):return(await Promise.resolve().then(()=>(Op(),_p))).WorkerSelenium;default:throw new C(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return U("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{U("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var pe,Lt,vt,Ur,P,M,j,K;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Go(r,n,e,i,o,t),this.combinedTestResults={};let T=((pe=i.company)==null?void 0:pe.ucid)||"",w=(Lt=i.company)==null?void 0:Lt.companyId,b=(vt=i.company)==null?void 0:vt.name,E=i.source||"cli",S=i.user,A=(Ur=i.company)==null?void 0:Ur.planType,D=(P=i.company)==null?void 0:P.isStartUp,R=(M=i.projectData)==null?void 0:M.name,N=(j=i.projectData)==null?void 0:j.type,k=i.lightweightMode,_=(K=i.gridData)==null?void 0:K.type,$=(Pe,Et,we,Ka,ei,Ja)=>(d++,Og({executionId:r,projectId:g,testId:Et,resultId:we,ucid:T,companyId:w,companyName:b,projectName:R,companyPlan:A,source:E,user:S,lightweightMode:k,isStartUp:D,projectType:N,appSource:Ja,gridType:_}),t.testStartAndReport(Pe,r,we,Ka,ei)),V=async(Pe,Et,we,Ka,ei,Ja)=>{var rd,sd,nd;d--;let et={...(k==null?void 0:k.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...i.host&&{gridHost:i.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((rd=i.gridData)==null?void 0:rd.name),et.gridType=(sd=i.gridData)==null?void 0:sd.type,et.gridProvider=(nd=i.gridData)==null?void 0:nd.provider):i.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):i.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):i.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):i.browserstack?et.gridName="browserstack-from-options":i.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Pe,we,r,Ka,ei,et).catch(_T=>Kp.error("testEndAndReport threw an error",{err:_T})),ei)return;this.combinedTestResults[we.resultId]=we,Lg({executionId:r,projectId:g,testId:Et,resultId:we.resultId,result:we,ucid:T,companyId:w,companyName:b,projectName:R,companyPlan:A,source:E,user:S,lightweightMode:k,logger:Kp,isStartUp:D,projectType:N,appSource:Ja}),l&&!we.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},z=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},ee=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...Tr(),refreshToken:$i(),authData:Tr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:fe},U("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,$,V,ee,z)});try{let u=await At(),f=await Wi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new Ht;return h}catch(u){throw Kp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var Zn,Va,Jp,Ga,sT=v(()=>{"use strict";Zn=I(require("lodash"));F();W();de();ne();$e();os();Iu();$u();ge();kt();eh();Y();rT();eo();({CLI_MODE:Va}=Ut),Jp=x("test-plan-runner"),Ga=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Wa(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,g,y);Object.assign(c,T)},u=async()=>{let g=di||i.parallel,y=!1;U("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);U("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};Dg({executionId:o,projectId:i.project}),U("right before runBeforeTests");try{return await m(),U("right before runTestPlanTests"),await u(),U("right after runTestPlanTests"),await f(),c}catch(g){if(Jp.error("error running test plan",{err:g}),g instanceof Ht)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Va.SELENIUM){let[{getSessionPlayer:E},{makeSDK:S}]=await Promise.all([Promise.resolve().then(()=>(Te(),Zt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=E();await A.closeBatch(o,S);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await Ll(i.project),Zn.default.isEmpty(g)||!o))return;let{runKey:E,url:S}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:S,apiKey:E}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,E,S;let c=re(),d=n.project;dc(c),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Do(m,n,o,a),f=Zn.default.chain(m).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);U("before testListInfoPromise");let T=await y;(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),U("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return U("before executionEnd"),await u.executionEnd(c),U("after executionEnd"),{results:w,executionId:c,testPlanName:i,configName:h}}async runTestPlans(e,t){Jp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Zn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a=await hl(o,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Va.APPIUM&&await su(e,r(c)),await oe(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 oe(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(S=>({executionId:S,status:ru(n[m][S])})),w=Object.keys(n[m]).map(S=>n[m][S]).reduce((S,A)=>Object.assign(S,A),{}),b=ru(w);Object.assign(i,w);let E=b?T[0].executionId:T.find(S=>!S.status).executionId;return await ml(o,m,{success:b,executions:T,executionId:E}),y})})}async runAnonymousTestPlan(e,t){var l;Jp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),U("before getSuite");let r=await If(e,t);if(U("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;U("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Va.APPIUM&&(a=await dn({appId:e.appId,projectId:e.project})),await oe(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!==Va.APPIUM&&await su(e,c),U("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return U("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=Pn(),r=[];qs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Zn.default.flattenDeep(r);return U("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),U("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}}});var aT={};H(aT,{init:()=>nR,run:()=>eR});async function UI(s){let e=s.project,t=await bl(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"),yn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ns}function BI(s,e){var i,o,a,l,c,d,m,u,f,h,g,y,T;let t=Ri(e.activePlan),r=s.parallel;if(t==="free"&&r>iT)throw new C(`The free plan allows only ${iT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let w=(i=s.projectData)!=null&&i.type?FI[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&w?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[w]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
|
|
410
|
-
We'll use the maximum of ${b} for now. To use more, you can adjust your command or upgrade your plan.`),s.parallel=b);let E=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.tunnel;if(s.tunnel&&!E)throw new
|
|
411
|
-
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((u=s.gridData)==null?void 0:u.type)===L.TESTIM_TVC){let
|
|
408
|
+
const downloadAndUploadFile = ${cI()};
|
|
409
|
+
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await rb(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ya,ba,ib=w(()=>{"use strict";ya=require("url");ue();ba=class extends G{async updateBaseUrl(e){let t=new ya.URL(e),r=new ya.URL(this.context.recordedBaseUrl),n=new ya.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 Ta,ob=w(()=>{"use strict";ue();F();Ta=class extends G{async performAction(){await ae(this.step.durationMS||0)}}});var wa,ab=w(()=>{"use strict";ue();wa=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var zn,cb=w(()=>{"use strict";ue();zn=class extends G{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var va,lb=w(()=>{"use strict";ue();va=class extends G{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var ub,Ep,Sp,pb=w(()=>{"use strict";ub=I(require("@applitools/spec-driver-webdriverio"));ai();Te();Ep=class{constructor(){let{EyeSdkBuilder:e}=X(),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:ub.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=X(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Sp=new Ep});var mb,db,Kn,fb=w(()=>{"use strict";mb=I(require("lodash"));ue();W();pb();db=C("pixel-validation-step-action"),Kn=class extends G{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Sp.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"};mb.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),db.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){db.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Sp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,Ip=w(()=>{"use strict";gs();Y();aa();vs=class extends ir{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await fs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ie?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var or,gb=w(()=>{"use strict";Ip();or=class extends vs{isFailedResult(e){return e===!1}}});var Ea,hb=w(()=>{"use strict";Ip();Ea=class extends vs{isFailedResult(e){return!e}}});var Sa,yb=w(()=>{"use strict";gs();ue();Y();Sa=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await ms(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof St?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ie?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var _r,bb=w(()=>{"use strict";ue();_r=class extends G{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,Tb=w(()=>{"use strict";ue();ye=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ia,wb=w(()=>{"use strict";ue();Ia=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ra,vb=w(()=>{"use strict";ue();Ra=class extends G{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function lI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Aa(s,e){lI(uI,e),e.registerLocateStepActionUtils(Vn.getUtils(s))}var uI,Rp=w(()=>{"use strict";yy();wy();Py();ky();Oy();My();Fy();By();jy();$y();Gy();Hy();qy();Jy();Qy();nb();ib();ob();ab();cb();lb();fb();gb();hb();yb();bb();Tb();wb();vb();uI={locate:Vn,scroll:ra,mouse:sa,submit:pa,text:ia,"special-key":ca,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":na,"text-validation":Hn,"wait-for-text-validation":Hn,"select-option":ua,"drop-file":fa,"input-file":ha,hover:da,navigation:ba,wheel:ma,sleep:Ta,refresh:wa,"keyboard-shortcut-step":la,"api-validation":zn,"api-action":zn,"api-code-step":Wt,"extract-text":va,"simple-ui-verification":Kn,"wait-for-simple-ui-verification":Kn,"cli-validation-download-file":_r,"cli-wait-for-download-file":_r,"network-validation-step":_r,"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":Ea,"node-package":Sa,"email-code-step":Wt,"cli-email-code-step":or,"sfdc-internal-test-step":Ra,"sfdc-recorded-step":Ia,"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 Eb,pI,Es,Ap=w(()=>{"use strict";Eb=["simple-ui-verification","wait-for-simple-ui-verification"],pI=[...Eb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Es=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=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 Eb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var Ib={};H(Ib,{SeleniumTestPlayer:()=>Jn});var Sb,dI,Jn,xp=w(()=>{"use strict";F();Sb=require("@applitools/eyes-sdk-core");Mn();Y();W();hp();dy();wp();ea();gy();vp();Te();Rp();Ap();dI=C("SeleniumTestPlayer"),Jn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(ta());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=X();this.driver=n??new xr;let d=new Zo(this.driver);this.stepActionFactory=new c(d),Aa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Xo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=fy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ts(this.driver),FrameLocator:m,portSelector:Qo,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=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=X(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ie&&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(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Pp={};H(Pp,{WorkerSelenium:()=>Cp});function fI(s){let{playback:e}=X().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>U(`Got event ${t}`))}var xa,mI,Cp,kp=w(()=>{"use strict";F();je();$n();W();Pt();io();ne();fp();Y();xp();Te();it();xa=C("worker-selenium"),mI=1e9,Cp=class extends _t{initPlayer(t){return new Jn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){U("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new bs(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),U("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),U("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,mI),await this.windowUtils.validatePageIsAvailable(),U("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`):(xa.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Wi(),initializedFromCache:Vi()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=X(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),fI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await 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,Me.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ie&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(xa.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=o.maxKeepAliveGap();f>=3e4&&(xa.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),U("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),U("right after super.runTestOnce in workerSelenium");let u=await d();return U("right after runSeleniumTest"),u}catch(u){throw xa.error("failed to run test once",{err:u}),u}}}});var Rb,Ab,Ge,gI,hI,_p,Tt,Ca=w(()=>{"use strict";Rb=I(require("ora")),Ab=require("jimp");de();Ve();ge();W();ne();Te();le();Ge=C("mobile-grid-service"),gI="https://tdc.tricentis-cloud.com",hI="https://ui.headspin.io",_p=class{constructor(){this.gridsAppIdGetter={[L.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[L.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[L.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[L.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[L.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[L.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===L.TESTIM_HEADSPIN?`${r||tc}/${sc}/devices`:t===L.TESTIM_TDC?`${r||rc}/${sc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:i})}catch(o){throw Ge.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw Ge.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await js(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===L.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===L.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([L.BROWSERSTACK,L.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,l,c;if(t===L.TESTIM_HEADSPIN||t===L.TESTIM_TDC){let d=await Nl({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:v}=X();y=v(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Tr(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),Ge.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=X(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await Ab.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/c.width,width:u,height:f}}catch(o){return Ge.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ls}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?hI:gI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await be(`${e}/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:l}=t,c=await this.getTmaDeviceDetails(l,e);return await Tr(a,n,i,o,"RUNNING",{device:c}),Ge.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:c}),c}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(O.flags.allowFixingAppIdStructure.isEnabled()&&(Ge.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Fl({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await un({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:i}){let a={[L.BROWSERSTACK]:{name:"Browserstack"},[L.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[L.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Rb.default)(`uploading app to ${a} please wait..`).start();try{Ge.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Ul({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){Ge.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else Ge.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===L.BROWSERSTACK||f===L.TESTIM_TVC||f===L.P_CLOUDY;if(g){let T=t.projectData.type,v=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});v&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!v&&y&&(Ge.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!v&&!y&&Ge.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Ls}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${nc}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?tc:rc}/${nc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Ed}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&Ge.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===L.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await Tc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await be(e,void 0,i)}},Tt=new _p});function xb({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!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!==L.TESTIM_TDC&&e.type!==L.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function TI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function wI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&O.flags.enableBatchHeadSpin.isEnabled(),d=o&&(O.flags.enableBatchTDC.isEnabled()||O.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=O.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:TI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Pa(s){return"id"in s?s.id:s.packageName}function vI(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function EI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=vI(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":Pa(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":Pa(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:i=""}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Pa(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:Pa(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Cb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o}){let a=wI(o.type,i,n);return EI({projectType:s,sessionCaps:a,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function _a({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 Oa({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===L.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?ic:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":ic:".*")}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 II(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...ka(s,Ss)}}function Pb(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function RI(s){return Pb(s,e=>e.startsWith("browserstack."),"browserstack.")}function AI(s){return Pb(s,e=>!e.startsWith("browserstack."))}function kb(s){return!s||!_b(s)?"2.0.0":s}function _b(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Ob({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=_b(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function ka(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:l}){let{osVersion:c,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=SI(i,s),h=_a({osVersion:c,mobileConfig:m}),g=Oa({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),y=He(n.editorUrl,n.project,o.testId,o.testResultId,o.branch);if(u!==L.TESTIM_TVC&&l)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");let T={device:g,os_version:h,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":y,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Lr({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=O.flags.enableAppium2pCloudy.isEnabled(),g=_a({osVersion:l,mobileConfig:d}),y=Oa({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),v={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...v,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Sd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=II(b)),t="",Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Ss}})}function PI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=_a({osVersion:l,mobileConfig:d}),f=Oa({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"],Ob({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},v={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:kb(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...ka(h,Ss),"sauce:options":{...T,...v,...(0,Or.omit)(g,"appiumVersion")}};return Lr({projectType:s,sessionCaps:b,appiumPrefix:Ss,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function kI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=_a({osVersion:l,mobileConfig:d}),f=Oa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=RI(n.browserstack),g=(0,Or.omit)(AI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:v}=n.browserstack||{},b=O.flags.enableAppium2BrowserStack.isEnabled();if(b||Ob({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let S={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":kb(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},A={"appium:platformVersion":u,"appium:deviceName":f,...ka(g,Ss),"bstack:options":{...S,...(0,Or.omit)(h,"appiumVersion")}};return Lr({projectType:s,sessionCaps:A,appiumPrefix:Ss,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let E={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:v||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...ka(h,"browserstack.")};return Lr({projectType:s,sessionCaps:E,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function _I(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Cb(s);if(L.TESTIM_TVC===s.gridInfo.type)return xI(s);if(L.P_CLOUDY===s.gridInfo.type)return CI(s);if(L.SAUCELABS===s.gridInfo.type)return PI(s);if(L.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:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Lb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);xb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=Tt.getGridConnection(e),l=_I(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=OI(r,i==null?void 0:i.mobile);if(!(0,Or.isEmpty)(T)){let v=Object.entries(T).map(([b,E])=>E.split(",").map(S=>S===".*"||S==="="?"":`${b}:${S}`).join(",")).join(" ").trim();l[`${y}:selector`]=v}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Op.default)("2m"),f=(0,Op.default)("12m"),h=pr(O.flags.appiumConnectionRetryCount.getValue(),m),g=pr(O.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function Db(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;xb({nativeAppMetadata:r,appPath:i,gridInfo:t}),bI({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 Tt.getGridDirectConnection(t,d),f=Cb({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Mb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Lr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function Nb(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Op,Or,Ss,yI,Lp=w(()=>{"use strict";Op=I(require("ms"));le();ne();Ca();Or=require("lodash");F();de();Ss="appium:",yI=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var La,Fb=w(()=>{"use strict";La=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 Da,Bb=w(()=>{"use strict";F();Da=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=zs;this.getLinksFromUnescapeHTML=Ks}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Dp,Ma,jb=w(()=>{"use strict";W();Dp=C("mobile-frame-locator-mock"),Ma=class{foundFrameCallback(){return Dp.info("foundFrameCallback-mock invoked"),{}}locate(){return Dp.info("locate-mock invoked"),{}}async findFrame(){return Dp.info("findFrame-mock invoked"),{}}}});var LI,Wb,$b,Is,Mp=w(()=>{"use strict";LI=I(require("webdriverio")),Wb=require("@applitools/eyes-sdk-core");Fb();wp();W();Bb();vp();Te();Rp();jb();Ap();$b=C("appium-test-player"),Is=class{constructor(e,t,r,n=LI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=X(),m=new Da(this.driver);this.stepActionFactory=new c(m),Aa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(ta()),this.sessionPlayer=new a(e,{tabService:new La,cookieUtils:void 0,FrameLocator:Ma,portSelector:Qo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Wb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),$b.info("appium session deleted",{...i}))}catch(o){$b.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=X();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function DI(s){return await be(`${s}/api/status`)}async function Vb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function Gb(s){if((await DI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Hb=w(()=>{"use strict";Ve()});var qb={};H(qb,{WorkerLocalTma:()=>Bp});var Dr,Np,Up,Fp,Bp,zb=w(()=>{"use strict";Ve();Lp();$n();F();W();Pt();Mp();Te();Hb();Ca();Dr=C("worker-appium"),Np=class extends Error{},Up=class extends Error{},Fp=class extends Error{},Bp=class extends _t{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Is(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}=X(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var S;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await Gb(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:A}=await Tt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:v,version:b},E]=await Promise.all([this.getAppStateFromDevice(o,a,T),Vb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Dr.info("device status and app state",{deviceStatus:E,appInstalled:v,version:b,executionId:this.executionId,testResultId:this.testResultId}),!v&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!v&&y&&(await this.installApp(o,a,y),Dr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let A={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(S=this.options.projectData)==null?void 0:S.name}-${this.options.project}`},D=Mb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),R={capabilities:{udid:a,...D}};Dr.info("requesting new appium session from TMA",{tmaSessionSettings:R,executionId:this.executionId,testResultId:this.testResultId});let N=await this.requestNewAppiumSessionFromTma(o,R,g);this.sessionData=N;let k=await m.attach({sessionId:N.sessionId,capabilities:D,options:{capabilities:D}});this.device=await Tt.updateTmaDeviceDetails(a,this.options,t),Dr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:k.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:k.capabilities})}catch(A){throw Dr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Fp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await be(o)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Mt(n);await Bs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Up(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Np(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=X(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw 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 Jb={};H(Jb,{WorkerAppium:()=>jp});var Kb,Mr,jp,Yb=w(()=>{"use strict";F();Lp();Kb=require("linkedom");$n();W();Pt();Mp();Te();Ca();ne();os();Mr=C("worker-appium"),jp=class extends _t{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n,a=this.options.projectData.type,l=await Tt.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=(a==="android"||a==="ios")&&await t.isTestRecordedWithEnhancedMode(),u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:m},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Tt.lockDevice(i,this.options.deviceUdid),h=await Db(f)):h=Lb(f),Mr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:d,capabilities:Nb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await o.remote(h),this.device=await Tt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,m);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),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}=X(),n=async()=>{try{await t.getOrientation()}catch(i){Mr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&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:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=X(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:v,port:b,path:E}=await Tt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${v}:${b}${E}`}else d=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Kb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((v,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:v,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Mr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await ce(u(),c)}catch(y){throw Mr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return`Testim/production:${qe()}`}}});var Na,Xb=w(()=>{"use strict";F();Mn();Y();Na=class{constructor(e){this.id=e;this.driver=new xr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof ie&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Qb,Ua,Zb=w(()=>{"use strict";Qb=I(require("ws"));F();Ua=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 Qb.default(this._cdpUrl,{timeout:e}),r=qt(i=>{t.once("open",i)}),n=qt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var Ba,$p,Fa,eT=w(()=>{"use strict";F();Ba=I(require("chrome-launcher"));Ku();Zb();mn();$p=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ua}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Mo({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...Ba.Launcher.defaultFlags().filter(v=>v!=="--disable-extensions")];this.chrome=await Ba.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 mr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),es(()=>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}},Fa=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new $p(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Wp={};H(Wp,{WorkerExtension:()=>Yn});function MI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function tT(s){return MI(s)?s:new Error(s)}var ut,Yn,ja=w(()=>{"use strict";je();Y();$n();F();W();Pt();ne();Xb();eT();it();ut=C("worker-ext"),Yn=class extends _t{initPlayer(){return this.options.useChromeLauncher?new Fa(this.id):new Na(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Wi(),initializedFromCache:Vi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;U("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Me.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ie))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:i,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(U("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw 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();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Me.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ie))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=Ws.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG),v=await gc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(v.success),v.reason)}catch(S){ut.error("Could not update the grid about the test status",{err:S})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),v.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})`),v.keepAliveIssue=b),{...v,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),tT(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),tT(h)}};t.driver.start();try{return await super.runTestOnce(e,t),U("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Gp={};H(Gp,{WorkerExtensionSingleBrowser:()=>Vp});var NI,UI,Vp,Hp=w(()=>{"use strict";je();F();W();up();Pt();ja();NI=C("base-worker"),UI=500,Vp=class extends Yn{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,i){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(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 i=this.handleQuarantine(t);if(i)return i;U("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ae(UI)}}});var qp,$a,rT=w(()=>{"use strict";Mn();de();je();Bu();it();Zu();Y();W();ne();Xh();Zi();qp=C("worker-manager"),$a=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(zb(),qb))).WorkerLocalTma:(await Promise.resolve().then(()=>(Yb(),Jb))).WorkerAppium;default:return Nn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Hp(),Gp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(ja(),Wp))).WorkerExtension}else switch(r){case(vr.find(n=>n===r)&&Nn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Hp(),Gp))).WorkerExtensionSingleBrowser;case vr.find(n=>n===r):return(await Promise.resolve().then(()=>(ja(),Wp))).WorkerExtension;case yn.find(n=>n===r):return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;default:throw new x(`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 U("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{U("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var pe,Ot,wt,Nr,P,M,j,K;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Vo(r,n,e,i,o,t),this.combinedTestResults={};let T=((pe=i.company)==null?void 0:pe.ucid)||"",v=(Ot=i.company)==null?void 0:Ot.companyId,b=(wt=i.company)==null?void 0:wt.name,E=i.source||"cli",S=i.user,A=(Nr=i.company)==null?void 0:Nr.planType,D=(P=i.company)==null?void 0:P.isStartUp,R=(M=i.projectData)==null?void 0:M.name,N=(j=i.projectData)==null?void 0:j.type,k=i.lightweightMode,_=(K=i.gridData)==null?void 0:K.type,$=(Ce,vt,we,za,Qn,Ka)=>(d++,Og({executionId:r,projectId:g,testId:vt,resultId:we,ucid:T,companyId:v,companyName:b,projectName:R,companyPlan:A,source:E,user:S,lightweightMode:k,isStartUp:D,projectType:N,appSource:Ka,gridType:_}),t.testStartAndReport(Ce,r,we,za,Qn)),V=async(Ce,vt,we,za,Qn,Ka)=>{var ed,td,rd;d--;let Ze={...(k==null?void 0:k.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...i.host&&{gridHost:i.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),i.grid||i.gridId?(Ze.gridName=i.grid||((ed=i.gridData)==null?void 0:ed.name),Ze.gridType=(td=i.gridData)==null?void 0:td.type,Ze.gridProvider=(rd=i.gridData)==null?void 0:rd.provider):i.localTmaUrl?(Ze.gridName="local-tma-from-options",Ze.gridType="local-tma"):i.useLocalChromeDriver?(Ze.gridName="local-chrome-driver-from-options",Ze.gridType="local-chrome"):i.useChromeLauncher?(Ze.gridName="chrome-launcher-from-options",Ze.gridType="local-chrome"):i.browserstack?Ze.gridName="browserstack-from-options":i.saucelabs&&(Ze.gridName="saucelabs-from-options"),await t.testEndAndReport(Ce,we,r,za,Qn,Ze).catch(_T=>qp.error("testEndAndReport threw an error",{err:_T})),Qn)return;this.combinedTestResults[we.resultId]=we,Lg({executionId:r,projectId:g,testId:vt,resultId:we.resultId,result:we,ucid:T,companyId:v,companyName:b,projectName:R,companyPlan:A,source:E,user:S,lightweightMode:k,logger:qp,isStartUp:D,projectType:N,appSource:Ka}),l&&!we.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},z=(Ce,vt)=>{this.combinedTestResults[vt.resultId]=vt,t.onTestIgnored(Ce,vt.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},ee=(Ce,vt)=>t.onGridSlot(Ce,vt);for(i.userData={loginData:{...br(),refreshToken:ji(),authData:br(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:fe},U("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,$,V,ee,z)});try{let u=await Rt(),f=await $i(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new Gt;return h}catch(u){throw qp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var Xn,Wa,zp,Va,sT=w(()=>{"use strict";Xn=I(require("lodash"));F();W();de();ne();je();ns();Eu();Bu();ge();Pt();eh();Y();rT();Zi();({CLI_MODE:Wa}=Nt),zp=C("test-plan-runner"),Va=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new $a(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,g,y);Object.assign(c,T)},u=async()=>{let g=ui||i.parallel,y=!1;U("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);U("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};Dg({executionId:o,projectId:i.project}),U("right before runBeforeTests");try{return await m(),U("right before runTestPlanTests"),await u(),U("right after runTestPlanTests"),await f(),c}catch(g){if(zp.error("error running test plan",{err:g}),g instanceof Gt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,v,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Wa.SELENIUM){let[{getSessionPlayer:E},{makeSDK:S}]=await Promise.all([Promise.resolve().then(()=>(Te(),Qt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=E();await A.closeBatch(o,S);return}let g;try{if(!((b=(v=(T=i.company)==null?void 0:T.activePlan)==null?void 0:v.premiumFeatures)!=null&&b.applitools)||(g=await _l(i.project),Xn.default.isEmpty(g)||!o))return;let{runKey:E,url:S}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:S,apiKey:E}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,E,S;let c=re(),d=n.project;uc(c),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Lo(m,n,o,a),f=Xn.default.chain(m).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);U("before testListInfoPromise");let T=await y;(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),U("before runTestAllPhases");let v=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return U("before executionEnd"),await u.executionEnd(c),U("after executionEnd"),{results:v,executionId:c,testPlanName:i,configName:h}}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 Xn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a=await fl(o,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new x(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new x(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Wa.APPIUM&&await tu(e,r(c)),await oe(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 oe(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(S=>({executionId:S,status:eu(n[m][S])})),v=Object.keys(n[m]).map(S=>n[m][S]).reduce((S,A)=>Object.assign(S,A),{}),b=eu(v);Object.assign(i,v);let E=b?T[0].executionId:T.find(S=>!S.status).executionId;return await pl(o,m,{success:b,executions:T,executionId:E}),y})})}async runAnonymousTestPlan(e,t){var l;zp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),U("before getSuite");let r=await If(e,t);if(U("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new x("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new x("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new x("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;U("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Wa.APPIUM&&(a=await un({appId:e.appId,projectId:e.project})),await oe(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!==Wa.APPIUM&&await tu(e,c),U("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return U("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=xn(),r=[];Gs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Xn.default.flattenDeep(r);return U("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),U("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}}});var aT={};H(aT,{init:()=>iR,run:()=>tR});async function FI(s){let e=s.project,t=await hl(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 Ds}function jI(s,e){var i,o,a,l,c,d,m,u,f,h,g,y,T;let t=Ii(e.activePlan),r=s.parallel;if(t==="free"&&r>iT)throw new x(`The free plan allows only ${iT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let v=(i=s.projectData)!=null&&i.type?BI[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&v?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[v]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
|
|
410
|
+
We'll use the maximum of ${b} for now. To use more, you can adjust your command or upgrade your plan.`),s.parallel=b);let E=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.tunnel;if(s.tunnel&&!E)throw new x("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let S=(m=(d=e.activePlan)==null?void 0:d.premiumFeatures)==null?void 0:m.runInTurboMode;s.lightweightMode&&!S&&(console.warn(`
|
|
411
|
+
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((u=s.gridData)==null?void 0:u.type)===L.TESTIM_TVC){let v=e.tvcLicense.expireAt||1;if(Date.now()>v&&!e.churnedByL2C)throw new x("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let b=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>b)throw new x(`Your license allows only ${b} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((g=s.gridData)==null?void 0:g.type)===L.TESTIM_TDC){let v=e.tdcLicense.expireAt||1;if(Date.now()>v)throw new x("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(n){let v=(T=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:T.resultRetention;if(n>v)throw new x(`Retention days (${n}) cannot be greater than the company's retention days (${v}). Run aborted`)}if(zt(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let v=e.tvcLicense,b=e.tdcLicense;if(v!=null&&v.isPaid||b!=null&&b.isPaid)return;let E=e==null?void 0:e.createdAt;if(new Date(E)<new Date(O.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let A=s.retries;A&&A>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function $I(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await FI(s)}catch(t){if([x,Ds].some(r=>t instanceof r))throw t;Kp.error("could not validate cli account",{err:t})}}function WI(s){let e=br();return yf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function VI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(O.flags.useNewWSCLI.isEnabled()&&!e&&!t)return yt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(jo(),$h));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>($o(),Gh));r.init(s)}}function GI(s,e){let{branch:t,autoDetect:r}=s;if(Tg(e,r),!e&&!r)throw new x(`branch ${t} does not exist, run aborted.`)}async function HI(s,e){let{id:t,type:r}=e,i=oT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=xn();i&&(s.sfdcCredential=await ul({projectId:t,branch:o}))}function qI(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=Ii(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<nT?nT:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(i),O.setIsStartUp(o),O.setPlanType(a),Ct.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function zI(s,e){s.editorUrl=_s||e.editorUrl}function KI(s,e){s.allGrids=e}function JI(s,e){s.authData=e}function YI(s,e){let{id:t,name:r,type:n,defaults:i}=e;O.setProjectId(t),O.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function XI(s){var e;s.gridData=await dg(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function QI(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function ZI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(gt("user-override-file",t),s.mockNetworkRules=await nf(s.overrideMappingFile))}async function eR(s,e){U("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await $I(s),U("in runRunner before tunnel.connect"),await mo(s),U("in runRunner after tunnel.connect");let a=await new Va(e).run(s);return U("before tunnel.disconnect"),await fo(s),await nR(s.slotService,t,s.company.companyId),U("after tunnel.disconnect and gridService.keepAlive.end"),a}function rR(s){var e;Ct.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
|
|
412
412
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
413
413
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
414
|
-
`)}function
|
|
415
|
-
Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),
|
|
414
|
+
`)}function sR(s,e,t){s==="redis"&&Rn.start(t,e),s==="mongo"&&Sn.start(e)}async function nR(s,e,t){s==="redis"&&await Rn.end(t,e),s==="mongo"&&await Sn.end(e)}async function iR(s){var h,g,y,T;U("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=VI(e,{disableResults:i||Boolean((t==null?void 0:t.disableResults)&&(r||n===q.SELENIUM)),disableRemoteStep:i||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,editorConfig:l,companyByProjectId:c,projectById:d,branchName:m,allGrids:u}=await pn(s);if(c.disabled)throw new x("The company is disabled.");if(d.disabled)throw new x("The project is disabled.");if(s.printGrids){let v=u.sort((b,E)=>b.type.localeCompare(E.type));console.table(v.reduce((b,E)=>{class S{constructor(R,N){this.Type=R,this.Browsers=N}}let A=Object.entries(E.browsers||{"N/A":""}).map(D=>D.join(":")).join(", ");return b[E.name]=new S(E.type,A),b},{})),process.exit(0)}if(await o,U("after featureFlagsReady and socketConnected"),zI(s,l),qI(s,c),YI(s,d),QI(s,d),GI(s,m),KI(s,u),JI(s,a),await HI(s,d),await XI(s),jI(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[df(s)]),O.flags.clearRunnerFileCache.isEnabled())try{await Kr(),Kp.info("runner file cache cleared")}catch(v){Kp.error("failed to clear runner file cache",{err:v})}(g=s.lightweightMode)!=null&&g.disableLabs||await Nn.loadLabFeatures(d.id,c.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(O.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((T=s.lightweightMode)==null?void 0:T.type)==="turboMode"&&console.log(`
|
|
415
|
+
Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),sR(s.slotService,e,c.id),WI(e),await ZI(s),rR(s);let f=xn();await Q.setOptions(s,f)}var oT,nT,iT,Kp,BI,tR,cT=w(()=>{"use strict";oT=I(require("lodash"));F();Tu();je();ns();os();ts();Eu();ge();it();Kt();W();Pt();de();ne();Y();sT();Fo();Zu();le();Pn();Kl();fn();nT=30*60*1e3,iT=1,Kp=C("runner");BI={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};tR=eR});function lT(s){s.get("/",(e,t)=>{let r=Jp();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Ki()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());ou({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var uT=w(()=>{"use strict";so();Yp();Vl()});var Xp,pT,Rs,Ga,dT=w(()=>{"use strict";Xp=I(require("chalk"));gs();pT=require("express");W();Y();Rs=C("cli-router"),Ga=(0,pT.Router)();Ga.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!l||typeof c!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d,nodePackageParams:n.nodePackageParams};try{let u=await fs(t,r,n,i,o,a,l,c,d);u.success||(console.log(Xp.default.red(u.result.resultValue)),Rs.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){Rs.error("failed to run cli code",{err:u,...m}),console.log(Xp.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});Ga.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:i,stepResultId:o,timeout:a}=s.body;if(!t||typeof i!="object"||!r||typeof n!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let l={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let c=await ms(t,r,n,i,o,a);Rs.info("installed packages successfully",l),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof St){Rs.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 ie){Rs.error("timeout installing node package",{err:c,...l}),e.status(200).json({success:!1,code:"timeout"});return}Rs.error("failed to install node packages",{err:c,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var mT=w(()=>{"use strict";dT()});var yT={};H(yT,{orchestrateRoutes:()=>oR});function oR(s){let e=(0,gT.default)();s(e),e.use(Qp.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,hT.default)()),e.use(Qp.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:$e||ld?"*":["http://localhost:3000","https://app.testim.io","https://staging.testim.io","https://playground.testim.io","https://app.staging.testim.cc","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return e.use("*",(0,fT.default)(r)),lT(e),e.use("/cliJs",Ga),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var fT,gT,Qp,hT,bT=w(()=>{"use strict";fT=I(require("cors")),gT=I(require("express")),Qp=I(require("body-parser")),hT=I(require("compression"));uT();mT();de()});var wT={};H(wT,{init:()=>aR});async function aR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(bT(),yT));return new Promise((i,o)=>{let a=()=>{};t&&(qm(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let l=n(a),c=TT.createServer(l);c.listen(s,e),c.on("error",d),c.on("listening",m);function d(u){if(u.syscall!=="listen")return o(u);switch(u.code){case"EACCES":case"EPERM":return o(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new x(`Port ${s} is already in use, is another Testim instance running?`));default:return o(u)}}function m(){let{port:u}=c.address();console.log(`Running on port: ${u}`),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 TT,vT=w(()=>{"use strict";TT=I(require("http"));it();Y()});var CT={};H(CT,{getStartedWithStart:()=>Jp,runAgentMode:()=>dR});async function dR(s){var r;let e;if(await hr(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 x('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(vT(),wT));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(xp(),Fe(Ib)))},6e3),t.init(s)}function Jp(){return AT}function ET(s){try{return process.kill(s,0)}catch{return!1}}async function mR(s,e,t){let r=ar.join(Ut,`chrome-${tn}-process`),n=3e3,i=()=>{xe.rmSync(r,{recursive:!0}),console.log(`
|
|
416
416
|
|
|
417
|
-
Browser session ended`),process.exit(0)};if(await he(r)){let f=JSON.parse(xe.readFileSync(r));if(ET(f.pid)){let h=()=>ET(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await
|
|
418
|
-
`).map(i=>i.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await
|
|
419
|
-
`):""}overrideMimeType(t){if([Ee.LOADING,Ee.DONE].includes(this.readyState))throw new
|
|
417
|
+
Browser session ended`),process.exit(0)};if(await he(r)){let f=JSON.parse(xe.readFileSync(r));if(ET(f.pid)){let h=()=>ET(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await Bi();await he(As)||await xe.promises.mkdir(As,{recursive:!0});let l=[...xT(As,e,t,o).desiredCapabilities.chromeOptions.args,...qa.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],c={GOOGLE_API_KEY:Rd,GOOGLE_DEFAULT_CLIENT_ID:Ad,GOOGLE_DEFAULT_CLIENT_SECRET:xd},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await qa.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:As,chromePath:o,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await mr(`localhost:${m.port}`)};return xe.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",i),m.process.once("close",i),{webdriverApi:u}}async function fR(s){let e=`${bd}/extension/testim-full-master.zip`,t=ar.basename(e),r=ar.join(Ut,t),n=ar.join(Ut,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await he(r)){let f=await xe.promises.stat(r);i=Date.now()-uR>f.mtimeMs}if(await xe.promises.mkdir(Ut,{recursive:!0}),i){let f=(0,IT.default)("Downloading Testim Editor").start();await Ke(e,r);try{await st(r,n)}catch{await xe.promises.rm(r,{recursive:!0,force:!0}),await Ke(e,r);try{await st(r,n)}catch{throw await xe.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 xe.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await xe.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await mR(s,o,n);await Xs({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=xT(As,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:l}=(Mn(),Fe(Sh)),{SeleniumPerfStats:c}=(cs(),Fe(Kg)),d=new l;d.seleniumPerfStats=new c;let m=await d.initClient(a);AT=!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 mr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function xT(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&i.push(`--load-extension=${t}`),{logLevel:lR,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function gR(){if(await he(Ha))try{let{webSocketDebuggerUrl:s}=await hR();await yR(s),await xe.promises.unlink(Ha)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await xe.promises.unlink(Ha)}}async function hR(){let s=await xe.promises.readFile(Ha,{encoding:"utf8"}),[e,t]=s.split(`
|
|
418
|
+
`).map(i=>i.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await mr(`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 qt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function bR(s,e=100){let t=new RT.default(s,{timeout:e}),r=qt(i=>{t.once("open",i)}).then(()=>{t.removeAllListeners()}),n=qt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}var ST,IT,RT,xe,ar,qa,lR,uR,As,pR,Ha,AT,Yp=w(()=>{"use strict";ST=I(require("ms")),IT=I(require("ora")),RT=I(require("ws")),xe=I(require("fs")),ar=I(require("path")),qa=I(require("chrome-launcher"));de();Zs();Y();el();F();lR=li?"verbose":"silent",uR=(0,ST.default)("1h"),As=ar.join(Ut,"profile"),pR="DevToolsActivePort",Ha=ar.join(As,pR);AT=!1});var iM=require("source-map-support/register");var oi=I(require("os")),Cs=I(require("url")),Ps=I(require("http")),Ja=I(require("https")),ei=I(require("form-data")),ti=class{constructor(){this.onloadstart=null;this.onprogress=null;this.onabort=null;this.onerror=null;this.onload=null;this.ontimeout=null;this.onloadend=null;this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]||=[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let i of r)i==null||i.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},ri=class extends ti{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(t!=null)if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let i=0;i<t.byteLength;i++)r[i]=n[i];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=t.byteOffset,i=new Uint8Array(t.buffer);for(let o=0;o<t.byteLength;o++)r[o]=i[o+n];this._body=r}else if(typeof t=="object"&&t instanceof ei.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()}},xs=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}},si=class extends Error{},ni=class extends Error{},ii=class extends Error{},cr=class extends Error{},Ee=class extends ti{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Ps.globalAgent;this.nodejsHttpsAgent=Ja.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 (${oi.type()} ${oi.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 ri(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&&!Cs.parse(r,!1,!0).protocol)throw new si("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new ii(`HTTP method ${t} is not allowed in XHR`);let i=this._parseUrl(r);n===void 0&&(n=!0),this._method=t,this._url=i,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(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 cr("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 cr("XHR readyState must be OPENED");if(this._request)throw new cr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new ni(`XHR request to ${this._url.href} failed: unsupported protocol '${this._url.protocol}'. Please use supported protocols like HTTP, HTTPS, or file.`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let r=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
|
|
419
|
+
`):""}overrideMimeType(t){if([Ee.LOADING,Ee.DONE].includes(this.readyState))throw new cr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new xs("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new ni("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(t){if(this._sync)throw new Error("Synchronous XHR processing not implemented");t!=null&&(this._method==="GET"||this._method==="HEAD")?t=null:t||="",this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let r=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,i=(this._url.protocol==="http:"?Ps:Ja).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 ei.default&&t.pipe(i),this._request=i,this.timeout&&i.setTimeout(this.timeout,()=>this._onHttpTimeout(i)),i.on("response",o=>this._onHttpResponse(i,o)),i.on("error",()=>this._onHttpRequestError(i)),this.upload._startUpload(i),this._request===i&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof ei.default&&Object.assign(this._headers,t.getHeaders()),this._headers.Connection="keep-alive",this._headers.Host=this._url.host,this._anonymous&&(this._headers.Referer="about:blank"),this._headers["User-Agent"]=this._userAgent,this.upload._finalizeHeaders(this._headers,this._loweredHeaders)}_onHttpResponse(t,r){if(this._request!==t)return;if([301,302,303,307,308].includes(r.statusCode)){this._url=this._parseUrl(r.headers.location),this._method="GET","content-type"in this._loweredHeaders&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),"Content-Type"in this._headers&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),this._sendHxxpRequest();return}this._response=r,this._response.on("data",i=>this._onHttpResponseData(r,i)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=Ps.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 xs(t);r.lengthComputable=this._lengthComputable,r.loaded=this._loadedBytes,r.total=this._totalBytes,this.dispatchEvent(r)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let r,n,i,o=this.nodejsBaseUrl===null?t:Cs.resolve(this.nodejsBaseUrl,t),a=Cs.parse(o,!1,!0);return a.hash=null,a.auth&&(i!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?i||(i=a.auth):(i||(i=a.substring(0,r)),n||(n=a.substring(r+1)))),(i||n)&&(a.auth=`${i}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let i=r.toLowerCase();this._privateHeaders[i]||(this._mimeOverride!==null&&i==="content-type"&&(n=this._mimeOverride),this._responseHeaders[i]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let i=0;i<t.length;i++)n[i]=t[i];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}},Pe=Ee;Pe.SyntaxError=si,Pe.ProgressEvent=xs,Pe.SecurityError=ii,Pe.XMLHttpRequest=Ee,Pe.InvalidStateError=cr,Pe.XMLHttpRequestUpload=ri,Pe.UNSENT=0,Pe.OPENED=1,Pe.HEADERS_RECEIVED=2,Pe.LOADING=3,Pe.DONE=4;Object.assign(global,{xhr2:Pe,XMLHttpRequest:Pe});var PT=I(require("semver"));je();Kl();Kt();Zs();var Zp=I(require("chalk")),kT=require("events");ne();mn();Y();ne();Gi();W();var cf=I(require("os")),Jl=I(require("path")),Yl=I(require("chalk")),Xi=require("fs");de();function lf(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=cf.homedir();(0,Xi.mkdirSync)(Jl.resolve(n,".testim_logs"),{recursive:!0});let i=Jl.resolve(n,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${i}`),fd&&console.log(`Call stack: ${s==null?void 0:s.stack}`),(t=s==null?void 0:s.message)!=null&&t.includes("Unable to compile TypeScript")&&((r=s.stack)!=null&&r.includes("runner/src"))&&process.argv.some(o=>o.includes("player-require-path"))&&(console.log(Yl.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(Yl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Xi.writeFileSync)(i,`${s}
|
|
420
420
|
${s==null?void 0:s.stack}
|
|
421
421
|
|
|
422
|
-
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}
|
|
422
|
+
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Ys();var pv=C("process-handler"),uf=!1;function dv(s){return s instanceof Error?1:uf?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(me.SKIPPED)||[t,i].includes(me.FAILED)&&n===Je.EVALUATING?!1:r!==!0)?1:0)}function mv(){try{Jt("chromedriver").stop()}catch{}}function pf(){uf=!0}async function Xl(s){s!=null&&s.stack&&(Qr?console.error(s,s.stack):lf(s)),mv(),await pv.waitForFlush(),process.exit(dv(s))}ge();W();le();var TR=C("cli-entry");function wR(s){if(!PT.satisfies(process.version,s))throw new x(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=18,t=20,r=Number(process.versions.node.split(".")[0]),n=new Date("2025-04-30T00:00:00.000Z"),i=n<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new x(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&i)throw new x(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(Zp.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function vR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(F(),J)),Promise.resolve().then(()=>(Nf(),Mf))]);U("Starting Testim.io CLI"),af(Xl);try{wR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await O.fetch();let t=await e.process();if(U("in main, after options.process"),dc(global.proxyUri),kT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,pc(t.project),bm("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:i}=await Promise.resolve().then(()=>(bn(),jf));return await i()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Kr(),await pn(t);let{preloadTests:i}=await Promise.resolve().then(()=>(io(),Wf));await i(t),!t.playerRequirePath&&t.mode!==q.EXTENSION&&await hr(t.playerLocation,t.canary);let o=await hm();o.success?console.log(`created prefetched data at ${ki()}`):console.error("failed to create prefetch data",o.error);return}let r=await Promise.resolve().then(()=>(cT(),aT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:i}=await Promise.resolve().then(()=>(Tu(),bu));await i(t);return}if(s.isAgentMode(t)){let{runAgentMode:i}=await Promise.resolve().then(()=>(Yp(),CT));return i(t)}if(t.saveRCALocally){let{initServer:i}=await Promise.resolve().then(()=>(Vu(),Qg)),{port:o}=await i(t);t.localRCASaver=`http://localhost:${o}`}t.exitCodeIgnoreFailingTests&&pf(),U("right before testRunner.init/prepareRunner.prepare"),await r.init(t);let n=await sf(t);return U("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof Fr)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Ml({...r,error:t.message}).catch(()=>{}),t instanceof x?(console.log(Zp.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"),Xl(s)});
|
|
423
423
|
//# sourceMappingURL=cli.js.map
|